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

标签 c# c#-4.0 c#-3.0

是否可以将不同类型的通用对象添加到列表中?如下图。

public class ValuePair<T>
{        
    public string Name { get; set;}
    public T Value { get; set;                     
}

假设我有所有这些对象...

 ValuePair<string> data1 =  new ValuePair<string>();
 ValuePair<double> data2 =  new ValuePair<double>();
 ValuePair<int> data3 =  new ValuePair<int>();

我想将这些对象保存在一个通用列表中。例如

List<ValuePair> list = new List<ValuePair>();

list.Add(data1);
list.Add(data2);
list.Add(data3);

这可能吗?

最佳答案

通常,您必须使用 List<object>或者创建一个非泛型基类,例如

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> .

现在,一个异常(exception):C# 4 中的协变/逆变类型。例如,您可以这样写:

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);

这不适用于您的情况,因为:

  • 您使用的是通用类,而不是接口(interface)
  • 您无法将其更改为通用协变 接口(interface),因为您有T “进入”“进入”API
  • 您正在使用值类型作为类型参数,并且它们不适用于通用变量(因此 IEnumerable<int> 不是 IEnumerable<object> )

关于c# - 将不同类型的通用对象添加到通用列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7088551/

相关文章:

c# - cancellationtoken如何停止continuewith?

c# - 异步 Json.net 反序列化

c# - 从列表中获取月份名称和年份

c# - CefSharp.BrowserSubprocess.exe 已停止工作

entity-framework - 如何使用 WCF 数据服务/OData 从 sproc 使用复杂对象?

c# - 为什么 .ForEach() 在 IList<T> 而不是 IEnumerable<T> 上?

c# - 将 IQueryable Where 与具有多个参数的表达式一起使用

c# - 在 aspx 网页上使用 JsonObject 的内容

c# - HttpUtility.ParseQueryString 奇怪的行为

c# - LINQ:将数组 [,] 转换为数组 []