泛型类型的集合 [英] Collection of generic types
本文介绍了泛型类型的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个泛型类:
public class MyClass<T>
{
public T Value;
}
我要实例的几个项目,如...
I want to instantiate several items such as...
new MyClass<string>
new MyClass<int>
...,并将它们添加到集合。我如何定义集合,以便它可以容纳泛型类型的列表?然后,我想在某个时候通过收集迭代,并使用Value属性。可能?
...and add them to a collection. How do I define the collection so that it can hold a list of generic types? I then want to iterate through the collection at some point, and use the Value property. Possible?
推荐答案
有从非通用基的泛型类继承,或实行非通用接口。然后你就可以有这种类型的集合,无论$ C $内施放c您用来访问集合的内容。
Have your generic class inherit from a non-generic base, or implement a non-generic interface. Then you can have a collection of this type and cast within whatever code you use to access the collection's contents.
下面是一个例子。
public abstract class MyClass
{
public abstract Type Type { get; }
}
public class MyClass<T> : MyClass
{
public override Type Type
{
get { return typeof(T); }
}
public T Value { get; set; }
}
// VERY basic illustration of how you might construct a collection
// of MyClass<T> objects.
public class MyClassCollection
{
private Dictionary<Type, MyClass> _dictionary;
public MyClassCollection()
{
_dictionary = new Dictionary<Type, MyClass>();
}
public void Put<T>(MyClass<T> item)
{
_dictionary[typeof(T)] = item;
}
public MyClass<T> Get<T>()
{
return _dictionary[typeof(T)] as MyClass<T>;
}
}
这篇关于泛型类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文