且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将不同类型的通用对象添加到通用列表中

更新时间:2022-11-21 09:48:52

通常,您必须使用 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&gt ;

现在,有一个 例外: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 an IEnumerable<object>)