我知道这个问题已经问了很多年,但它仍然可以公开查看。
在这个主题中和这个主题中有几个提出的例子:
确定类型是否为字典[重复]
但是有一些不匹配,所以我想分享我的解决方案
简短回答:
var dictionaryInterfaces = new[]
{
typeof(IDictionary<,>),
typeof(IDictionary),
typeof(IReadOnlyDictionary<,>),
};
var dictionaries = collectionOfAnyTypeObjects
.Where(d => d.GetType().GetInterfaces()
.Any(t=> dictionaryInterfaces
.Any(i=> i == t || t.IsGenericType && i == t.GetGenericTypeDefinition())))
更详细的回答:
我认为这是人们犯错误的原因:
typeof(IDictionary<,>).IsAssignableFrom(typeof(IDictionary<,>))
typeof(IDictionary<int, int>).IsAssignableFrom(typeof(IDictionary<int, int>));
typeof(IDictionary<int, int>).IsAssignableFrom(typeof(Dictionary<int, int>));
typeof(IDictionary<,>).IsAssignableFrom(typeof(Dictionary<,>));
假设我们有以下类型:
public class CustomReadOnlyDictionary : IReadOnlyDictionary<string, MyClass>
public class CustomGenericDictionary : IDictionary<string, MyClass>
public class CustomDictionary : IDictionary
以及这些实例:
var dictionaries = new object[]
{
new Dictionary<string, MyClass>(),
new ReadOnlyDictionary<string, MyClass>(new Dictionary<string, MyClass>()),
new CustomReadOnlyDictionary(),
new CustomDictionary(),
new CustomGenericDictionary()
};
因此,如果我们使用.IsAssignableFrom()方法:
var dictionaries2 = dictionaries.Where(d =>
{
var type = d.GetType();
return type.IsGenericType && typeof(IDictionary<,>).IsAssignableFrom(type.GetGenericTypeDefinition());
});
我们将不会获得任何实例。
所以最好的方法是获取所有接口,并检查它们中是否有任何字典接口:
var dictionaryInterfaces = new[]
{
typeof(IDictionary<,>),
typeof(IDictionary),
typeof(IReadOnlyDictionary<,>),
};
var dictionaries2 = dictionaries
.Where(d => d.GetType().GetInterfaces()
.Any(t=> dictionaryInterfaces
.Any(i=> i == t || t.IsGenericType && i == t.GetGenericTypeDefinition())))