C# 如何确定对象';s type是IEnumerable的一个子类<;T>;对于任何值类型T?
我需要验证一个对象,看看它是null、值类型还是C# 如何确定对象';s type是IEnumerable的一个子类<;T>;对于任何值类型T?,c#,.net,generics,reflection,C#,.net,Generics,Reflection,我需要验证一个对象,看看它是null、值类型还是IEnumerable,其中T是值类型。到目前为止,我已经: if ((obj == null) || (obj .GetType().IsValueType)) { valid = true; } else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>))) { // TODO: check whether the generic parameter
IEnumerable
,其中T
是值类型。到目前为止,我已经:
if ((obj == null) ||
(obj .GetType().IsValueType))
{
valid = true;
}
else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>)))
{
// TODO: check whether the generic parameter is a value type.
}
if((obj==null)||
(obj.GetType().IsValueType))
{
有效=真;
}
else if(obj.GetType().IsSubclassOf(typeof(IEnumerable)))
{
//TODO:检查泛型参数是否为值类型。
}
所以我发现这个对象是null,一个值类型,或者对于某些T
,它是IEnumerable
;如何检查T
是否为值类型?(编辑-增值类型位)
您需要检查它实现的所有接口(注意,对于多个T
,理论上它可以实现IEnumerable
):
foreach(在obj.GetType().GetInterfaces()中键入interfaceType)
{
if(interfaceType.IsGenericType
&&interfaceType.GetGenericTypeDefinition()==typeof(IEnumerable))
{
类型itemType=interfaceType.GetGenericArguments()[0];
如果(!itemType.IsValueType)继续;
WriteLine(“IEnumerable of-”+itemType.FullName);
}
}
你能用GetGenericaArguments
做点什么吗?我的泛型贡献,检查给定类型(或其基类)是否实现了T类型的接口:
public static bool ImplementsInterface(this Type type, Type interfaceType)
{
while (type != null && type != typeof(object))
{
if (type.GetInterfaces().Any(@interface =>
@interface.IsGenericType
&& @interface.GetGenericTypeDefinition() == interfaceType))
{
return true;
}
type = type.BaseType;
}
return false;
}
GetInterfaces是否具有足够的递归性,意味着您不需要担心父类型的上升?您不需要递归。类要么实现接口,要么不实现接口。这是一个简单的列表,不管接口本身如何“继承”彼此。
public static bool ImplementsInterface(this Type type, Type interfaceType)
{
while (type != null && type != typeof(object))
{
if (type.GetInterfaces().Any(@interface =>
@interface.IsGenericType
&& @interface.GetGenericTypeDefinition() == interfaceType))
{
return true;
}
type = type.BaseType;
}
return false;
}