我想确定一个给定的Type
对象是否引用了一个通用字典。为了实现这一点,我尝试了来自this answer的解决方案。但令我惊讶的是,下面的测试代码会打印not a generic dictionary!
private void Test()
{
var dict = new Dictionary<string, string>();
var type = dict.GetType();
if (type.IsGenericType &&
typeof(IDictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition()))
Console.WriteLine("a generic dictionary");
else
Console.WriteLine("not a generic dictionary!");
}
为什么IDictionary`2
不能从Dictionary`2
中分配,或者我犯了什么根本错误呢?
如果有问题,我将在Visual 2015中以.NET 4.6为目标进行此操作。
发布于 2018-04-17 11:43:40
您需要搜索类型的接口,并检查是否有IDictionary<K, V>
接口的实例化:
bool isDict = type.GetInterfaces().Any(it => it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IDictionary<,>));
https://stackoverflow.com/questions/49876877
复制相似问题