gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:07:33 25 4
gpt4 key购买 nike

我有一个方法接受类型为 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

有没有更好的办法?

最佳答案

我认为你把这个复杂化了一点。如果您真的想使用 IEnumerable 但排除 System.String,为什么不直接在代码中这样做呢?

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

关于c# - 测试类型是否为集合的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1180648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com