我想检查泛型变量是否属于某种类型,但不想检查泛型部分。检查通用类型
比方说,我有一个变量List<int>
和另一个List<double>
。我只是想检查它是否List<>
型
if(variable is List) {}
而且不
if (variable is List<int> || variable is List<double>) {}
这可能吗?
感谢
我想检查泛型变量是否属于某种类型,但不想检查泛型部分。检查通用类型
比方说,我有一个变量List<int>
和另一个List<double>
。我只是想检查它是否List<>
型
if(variable is List) {}
而且不
if (variable is List<int> || variable is List<double>) {}
这可能吗?
感谢
variable.GetType().IsGenericType &&
variable.GetType().GetGenericTypeDefinition() == typeof(List<>)
当然,如果变量是List<T>
型的,而不是派生类这仅适用。如果你要检查它是否是List<T>
或继承它,你应该遍历继承层次,并检查上面的语句为每个基类:
static bool IsList(object obj)
{
Type t = obj.GetType();
do {
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
return true;
t = t.BaseType;
} while (t != null);
return false;
}
Type t = variable.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
{
// do something
}
您可以通过反射测试的确切类型:
object list = new List<int>();
Type type = list.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
Console.WriteLine("is a List-of-" + type.GetGenericArguments()[0].Name);
}
就个人而言,虽然,我会寻找IList<T>
- 比混凝土List<T>
更灵活:
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Console.WriteLine("Is an IList-of-" +
interfaceType.GetGenericArguments()[0].Name);
}
}
marc,是不是'type.GetGenericTypeDefinition()== typeof(List <>)'足以检查? – 2013-03-04 05:33:46
@Royi如果你的意思是第一块代码,那么否:如果GetGenericTypeDefinition()不是泛型类型,它将被抛出;如果你的意思是第二块:“列表”的类型不仅仅是“列表
好的谢谢... – 2013-03-04 06:41:38
GetGenericTypeDefinition()比没有参数的MakeGenericType()更自然。 – weiqure 2009-08-14 09:05:47
@weiqure:Ooooops。对。其实是错误的。固定。 – 2009-08-14 09:07:24
是的。完整的代码是第二个。第一行只是关注这个想法。 – 2009-08-14 09:12:16