c# - 对于任何值类型 T,如何确定对象的类型是否是 IEnumerable<T> 的子类?

标签 c# .net generics reflection

我需要验证一个对象以查看它是空值、值类型还是 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/

相关文章:

c# - DataTable 未分配

javascript - 在 C# 中使用 javascript/jquery 函数在 5 秒后隐藏一个 div 和标签

.net - 使用 Twitter 通过 Azure 移动服务重新进行身份验证

c++ - 在 C++ 中实现 'bounded genericity'

generics - C# 将 ArrayList 自定义排序转换为通用 List<T> 自定义排序

c# - 休眠子集合

c# - 在 WPF 中渲染 UIElement 期间等待屏幕

.net - 使用 StackPanel 作为 ContentControl (WPF)

c# - 插入具有一对多关系的新记录/更新现有记录

c# - 通用表达式树,每个提供的属性都有 'OR' 子句