开发者

How to detect if collection contain instance of specific type?

开发者 https://www.devze.com 2022-12-24 19:32 出处:网络
Suppose I create collection like Collection<IMyType> coll; Then I have many implelentations of IMyTypem like, T1, T2, T3...

Suppose I create collection like

Collection<IMyType> coll;

Then I have many implelentations of IMyTypem like, T1, T2, T3...

Then I want know if the collection coll contains a instance of type T1. So I want to write a method like

public bool ContainType( <T>){...}

here the par开发者_运维技巧am should be class type, not class instance. How to write code for this kind of issue?


You can do:

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

And then call it like:

 bool hasType = coll.ContainsType(typeof(T1));

If you want to see if a collection contains a type that is convertible to the specified type, you can do:

bool hasType = coll.OfType<T1>().Any();

This is different, though, as it will return true if coll contains any subclasses of T1 as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消