简体   繁体   English

测试对象是否为任何泛型类型实现通用接口

[英]Test whether an object implements a generic interface for any generic type

I want to test an object to see if it implements IDictionary<TKey,TValue> but I don't care what TKey and TValue are. 我想测试一个对象,看它是否实现了IDictionary<TKey,TValue>但我不关心TKeyTValue是什么。

I can test if is a concrete instance of the framework Dictionary<,> like this: 我可以测试是否是框架Dictionary<,>的具体实例Dictionary<,>如下所示:

bool isDict = type.IsGenericType && 
    (typeof(Dictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition());

but I can't think of a way to test for something that implements IDictionary<,> . 但我想不出一种方法来测试实现IDictionary<,>东西。 This technique doesn't work for the interface; 这种技术不适用于界面; IsAssignableFrom return false if I test against the generic base type IDictionary<,> , which seems odd since it works for the concrete type. 如果我对通用基类型IDictionary<,>测试,则IsAssignableFrom返回false,这似乎很奇怪,因为它适用于具体类型。

Normally you would use is to test if something implements an interface, but of course this only works if I want to test for a specific generic interface. 通常你会使用is来测试某些东西是否实现了一个接口,当然这只有在我想测试一个特定的通用接口时才有效。 Or I would just test for a common ancestral interface, but unlike other generic data structures such as IList<> and ICollection<> , there is no unique non-generic interface from which the generic IDictionary<TKey,TValue> inherits. 或者我只测试一个共同的祖先接口,但与其他通用数据结构(如IList<>ICollection<> ,没有唯一的非泛型接口,泛型IDictionary<TKey,TValue>继承该接口。

How about something like 怎么样的

return type.GetInterfaces()
           .Where(t => t.IsGenericType)
           .Select(t => t.GetGenericTypeDefinition())
           .Any(t => t.Equals(typeof(IDictionary<,>)));

which I'm sure that you can easily generalize for any generic type definition. 我相信你可以很容易地推广任何泛型类型定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM