如何检测集合是否包含特定类型的实例?

Ken*_*hou 7 c# collections

假设我创建了类似的集合

Collection<IMyType> coll;
Run Code Online (Sandbox Code Playgroud)

然后我有许多实现,IMyTypem如T1,T2,T3 ...

然后我想知道集合coll是否包含T1类型的实例.所以我想写一个像这样的方法

public bool ContainType( <T>){...}
Run Code Online (Sandbox Code Playgroud)

这里param应该是类类型,而不是类实例.如何为这类问题编写代码?

Ree*_*sey 9

你可以做:

 public bool ContainsType(this IEnumerable collection, Type type)
 {
      return collection.Any(i => i.GetType() == type);
 }
Run Code Online (Sandbox Code Playgroud)

然后把它称为:

 bool hasType = coll.ContainsType(typeof(T1));
Run Code Online (Sandbox Code Playgroud)

如果要查看集合是否包含可转换为指定类型的类型,您可以执行以下操作:

bool hasType = coll.OfType<T1>().Any();
Run Code Online (Sandbox Code Playgroud)

但是,这是不同的,因为如果coll包含T1的任何子类,它将返回true.