gpt4 book ai didi

C# 多个泛型约束

转载 作者:IT王子 更新时间:2023-10-29 04:29:56 25 4
gpt4 key购买 nike

我想知道是否可以添加多个通用约束?

我有一个采用对象(电子邮件、电话或地址)的 Add 方法,所以我在想:

public void Add<T>(T Obj) 
where T : Address
where T : Email
where T : Phone
{
if (Obj is Address)
m_Address.Add(Obj as Address);
else if (Obj is Email)
m_Email.Add(Obj as Email);
else
m_Phone.Add(Obj as Phone);
}

但我不断得到:

“已经为类型参数‘T’指定了约束子句。必须在单个 where 子句中指定类型参数的所有约束。”

最佳答案

你不能那样做。为什么不只拥有三个方法,让编译器为您完成繁重的工作?

public void Add(Address address) { m_Address.Add(address); }
public void Add(Email email) { m_Email.Add(email); }
public void Add(Phone phone) { m_Phone.Add(phone); }

关于C# 多个泛型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1176908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com