我需要验证一个对象以查看它是空值、值类型还是 IEnumerable<T>
其中 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.
}
所以我发现该对象为 null、值类型或 IEnumerable<T>
对于一些 T
;我该如何检查 T
是值类型?
最佳答案
(编辑 - 增值类型位)
您需要检查它实现的所有接口(interface)(请注意,理论上它可以为多个 IEnumerable<T>
实现 T
):
foreach (Type interfaceType in obj.GetType().GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
Type itemType = interfaceType.GetGenericArguments()[0];
if(!itemType.IsValueType) continue;
Console.WriteLine("IEnumerable-of-" + itemType.FullName);
}
}
关于c# - 对于任何值类型 T,如何确定对象的类型是否是 IEnumerable<T> 的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/637987/