测试类型是否为集合的最佳方法

问题描述 投票:0回答:3

我有一个接受 System.Object 类型的参数 obj 的方法

现在我想检查 obj 的实际类型是否是:

    集合类型(IEnumerable)。
  • 还有什么吗
我第一个想到的办法是:

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

有更好的方法吗?

c# .net ienumerable
3个回答
10
投票
我认为你把这件事搞得太复杂了。如果您确实想使用 IEnumerable 但排除 System.String,为什么不直接在代码中执行此操作呢?

public static bool IsCollection(object obj) { return obj is IEnumerable && !(obj is String); }
    

5
投票
如果您真的只想测试:

bool isCollection = obj.GetType().GetInterfaces() .Any(iface => iface.IsGenericType && iface.GetGenericTypeDefinition() == typeof(ICollection<>))
但坦率地说,如果你真的只想特殊情况

string

(顺便问一下,为什么?),那就这样做吧。例如,如果您测试 
ICollection<>
,您将无缘无故地将 LINQ 查询的结果视为“非集合”。


-1
投票
如果您想对任何列表/集合/IEnumerable 类型(包括可空值)进行检查并获得 true,但对字符串类型获得 false,则

private static bool IsIEnumerable(Type requestType) { var isIEnumerable = typeof(IEnumerable).IsAssignableFrom(requestType); var notString = !typeof(string).IsAssignableFrom(requestType); return isIEnumerable && notString; }
    
© www.soinside.com 2019 - 2024. All rights reserved.