如何在C#中传递通配符
我有以下内容:
public class Foo : Goo where T: SomeClass, new()
我知道 ? 在C#中不是一个真正的通配符,但是,你如何在C#中正确地编写它,以便SomeClass可以将任何类作为参数? 我尝试使用对象,但后来我得到一个错误“……没有来自……的隐式引用转换”
谢谢!
你必须指定第二种类型的参数(即我的样本中的Y
),注意Y
可以是任何东西,因为没有限制,甚至与T
相同。
public class Foo : Goo where T: SomeClass, new()
另一个选择是只指定第二个类,如果你只需要在generics类中使用SomeClass
,则不需要new()限制,因为编译器事先知道SomeClass
具有默认构造函数:
public class Foo : Goo{ public SomeClass Value; public void Setup() { Value = new SomeClass (); } }