将不同类型的通用对象添加到通用列表中
是否可以将不同类型的通用对象添加到列表中?如下。
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);
是否可能?
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);
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一般来说,您必须使用
List
然后您可以拥有
List
。现在,有一个例外:C# 4 中的协变/逆变类型。例如,您可以编写:
这不适用于您的情况,因为:
T
“进”和“出”接口APIIEnumerable
不是IEnumerable
In general, you'd have to either use a
List<object>
or create a non-generic base class, e.g.Then you can have a
List<ValuePair>
.Now, there is one exception to this: covariant/contravariant types in C# 4. For example, you can write:
This isn't applicable in your case because:
T
going "in" and "out" of the APIIEnumerable<int>
isn't anIEnumerable<object>
)除非您有一个带有
ValuePair的非通用基本类型
(它也适用于接口),或使用ValuePair
。 :ValuePairList
Not unless you have a non-generic base-type
ValuePair
withValuePair<T> : ValuePair
(it would work for an interface too), or useList<object>
. Actually, though, this works reasonably:不,这是不可能的。根据您的情况,您可以创建一个派生自
ValuePair
的基类ValuePair
。取决于您的目的。No, it is not possible. You could create, in your case, a base class
ValuePair
from whichValuePair<T>
derives. Depends on your purposes.据我所知这是不可能的。
该行:
您在示例中编写的内容没有为 T 提供具体类型,这就是问题所在,一旦通过它,您只能添加该特定类型的对象。
it's not possible as far as I know.
the line:
you wrote in your sample is not providing a concrete type for T and this is the issue, once you pass it, you can only add object of that specific type.