初始化未知类型的通用对象 [英] Initialize generic object with unknown type
问题描述
我怎么能初始化包含通用对象,其类型可以是不同的列表
How can I initialize a list containing generic objects whose types can be different?
例如,我有以下几点:
this.Wheres = new List<Where<>>();
如你所知,<>不是有效的语法。但是,有时类型传递到哪里将是一个字符串,有时会日期时间,等我尝试使用对象初始化类型,但这并不能工作。
As you know, <> is not valid syntax. However, sometimes the type passed to Where will be a string and sometimes it will be DateTime, etc. I tried using object as the initialized type, but that doesn't work either.
推荐答案
好了,你还没有真正给予足够的情况下(这是什么SqlWhere?),但通常你会使用一个类型参数:
Well, you haven't really given enough context (what's SqlWhere?) but normally you'd use a type parameter:
public class Foo<T>
{
private IList<T> wheres;
public Foo()
{
wheres = new List<T>();
}
}
如果你想有一个单一的集合包含多个不相关类型值的,但是,你将不得不使用列表<对象>
If you want a single collection to contain multiple unrelated types of values, however, you will have to use List<object>
这篇关于初始化未知类型的通用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!