我有一个类型。
我如何判断它是否是 IEnumerable<>
?
这些:
typeof(IEnumerable<>).IsAssignableFrom(memberType);
typeof(IEnumerable<object>).IsAssignableFrom(memberType);
对于 IEnumerable<int>
返回 false
鉴于此:
typeof(IEnumerable).IsAssignableFrom(memberType);
对字符串返回 true。
最佳答案
反射(reflection)很有趣;旁注:请记住,您可以实现 IEnumerable<X>
和 IEnumerable<Y>
(等)在同一类型上,所以为了简单起见,我只是报告第一个发现的任意:
static void Main()
{
Console.WriteLine(FindFirstIEnumerable(typeof(int))); // null
Console.WriteLine(FindFirstIEnumerable(typeof(string))); // System.Char
Console.WriteLine(FindFirstIEnumerable(typeof(Guid[]))); // System.Guid
Console.WriteLine(FindFirstIEnumerable(typeof(IEnumerable<float>))); // System.Single
}
static Type FindFirstIEnumerable(Type type)
{
if (type == null || !typeof(IEnumerable).IsAssignableFrom(type))
return null; // anything IEnumerable<T> *must* be IEnumerable
if (type.IsInterface && type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
return type.GetGenericArguments()[0];
}
foreach(var iType in type.GetInterfaces())
{
if (iType.IsGenericType &&
iType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
return iType.GetGenericArguments()[0];
}
}
return null;
}
关于c# - 如何判断某物是否为 IEnumerable<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58226119/