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.
精彩评论