更新时间: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> ;
。
现在,有一个 例外: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>
)T
going "in" and "out" of the APIIEnumerable<int>
isn't an IEnumerable<object>
)