将不同类型的通用对象添加到通用列表中 [英] Adding different type of generic objects into generic list
本文介绍了将不同类型的通用对象添加到通用列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将不同类型的通用对象添加到列表中?如下。
Is it possible to add different type of generic objects to a list?. As below.
public class ValuePair<T>
{
public string Name { get; set;}
public T Value { get; set;
}
并说我拥有所有这些对象...
and let say I have all these objects...
ValuePair<string> data1 = new ValuePair<string>();
ValuePair<double> data2 = new ValuePair<double>();
ValuePair<int> data3 = new ValuePair<int>();
我想将这些对象保存在通用列表中,例如
I would like to hold these objects in a generic list.such as
List<ValuePair> list = new List<ValuePair>();
list.Add(data1);
list.Add(data2);
list.Add(data3);
有可能吗?
推荐答案
通常,您必须使用 List< object>
或创建非通用基类,例如
In general, you'd have to either use a List<object>
or create a non-generic base class, e.g.
public abstract class ValuePair
{
public string Name { get; set;}
public abstract object RawValue { get; }
}
public class ValuePair<T> : ValuePair
{
public T Value { get; set; }
public object RawValue { get { return Value; } }
}
然后,您可以拥有 List< ValuePair> ;
。
现在,有一个 例外:C#4中的协变/反变量类型。例如,您可以编写:
Now, there is one exception to this: covariant/contravariant types in C# 4. For example, you can write:
var streamSequenceList = new List<IEnumerable<Stream>>();
IEnumerable<MemoryStream> memoryStreams = null; // For simplicity
IEnumerable<NetworkStream> networkStreams = null; // For simplicity
IEnumerable<Stream> streams = null; // For simplicity
streamSequenceList.Add(memoryStreams);
streamSequenceList.Add(networkStreams);
streamSequenceList.Add(streams);
这不适用于您的情况,因为:
This isn't applicable in your case because:
- 您正在使用泛型类,而不是接口
- 您无法将其更改为泛型协变量接口,因为您有
T
进入了API的和出 - 您将值类型用作类型参数,而这些值类型不适用于泛型变量(因此
IEnumerable< int>
不是IEnumerable< object>
)
- You're using a generic class, not an interface
- You couldn't change it into a generic covariant interface because you've got
T
going "in" and "out" of the API - You're using value types as type arguments, and those don't work with generic variable (so an
IEnumerable<int>
isn't anIEnumerable<object>
)
这篇关于将不同类型的通用对象添加到通用列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文