加入通用对象泛型列表在C# [英] Adding generic object to generic list in C#
问题描述
我所在班级的相关部分看起来像
I have class where the relevant part looks like
class C {
void Method<T>(SomeClass<T> obj) {
list.Add(obj);
}
List<?> list = new List<?>();
}
我应该如何定义列表中,以便类编译?
How should I define the list so that the class compiles?
我想类型的列表列表< SomeClass的<>>
,即<$ C的对象列表$ C> SomeClass的,其中每个对象都可以有任何类型的参数。 ?在Java
构造允许这一点;什么是C#相同呢?如果没有这样的东西存在,是有一个合适的解决方法吗? (A 列表<对象>
会做,但是是极其丑陋)
I want a list of type List<SomeClass<?>>
, that is a list of objects of SomeClass
where each object can have any type parameter. The Java ?
construct allows this; what is the C# equivalent? If no such thing exists, is there a suitable workaround? (A List<object>
would do but is terribly ugly.)
推荐答案
我不认为你可以在C#中做到这一点...你将不得不类型参数添加到类:
I don't think you can do this in C#... you would have to add the type parameter to the class:
class C<T> {
void Method(SomeClass<T> obj) {
list.Add(obj);
}
List<SomeClass<T>> list = new List<SomeClass<T>>();
}
另一种选择是使用一个接口:
The other option would be to use an interface:
class C {
void Method<T>(T obj)
where T : ISomeClass {
list.Add(obj);
}
List<ISomeClass> list = new List<ISomeClass>();
}
这篇关于加入通用对象泛型列表在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!