我有一个接受 System.Object 类型的参数 obj 的方法
现在我想检查 obj 的实际类型是否是:
if (obj is IEnumerable)
// obj is a collection
但是 System.String 实现了 IEnumerable,并且
我不想将字符串视为集合。
我想到的第二种方法是测试 ICollection 而不是 IEnumerable,因为 IEnumerable 更多的是一个潜在的集合而不是实际的集合。这会遗漏字符串,但也会遗漏 ICollection-Of-T,因为它不继承 ICollection(IEnumerable-Of-T 是唯一向后兼容的通用集合抽象 - 它继承 IEnumerable)。所以我想最好的方法是:
if (obj is string)
// not a collection
else if (obj is IEnumerable)
// collection
else
// not a collection
有更好的方法吗?
public static bool IsCollection(object obj) {
return obj is IEnumerable && !(obj is String);
}
bool isCollection = obj.GetType().GetInterfaces()
.Any(iface => iface.IsGenericType && iface.GetGenericTypeDefinition() == typeof(ICollection<>))
但坦率地说,如果你真的只想特殊情况string
(顺便问一下,为什么?),那就这样做吧。例如,如果您测试
ICollection<>
,您将无缘无故地将 LINQ 查询的结果视为“非集合”。
private static bool IsIEnumerable(Type requestType)
{
var isIEnumerable = typeof(IEnumerable).IsAssignableFrom(requestType);
var notString = !typeof(string).IsAssignableFrom(requestType);
return isIEnumerable && notString;
}