因为从.GetGenericTypeDefinition().GetInterfaces() 返回的接口不是“泛型类型定义”(它们的IsGenericTypeDefinition 是false),所以它们不能严格等于IDictionary<,>(即泛型类型定义, IsGenericTypeDefinition 即 true)。
第二段代码从接口深入到它们的泛型类型定义,让您进行比较。
一个简单的例子:
class MyDictionary<TKey2, TValue2> : IDictionary<TKey2, TValue2>
{
public TValue2 this[TKey2 key] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public ICollection<TKey2> Keys => throw new NotImplementedException();
public ICollection<TValue2> Values => throw new NotImplementedException();
public int Count => throw new NotImplementedException();
public bool IsReadOnly => throw new NotImplementedException();
public void Add(TKey2 key, TValue2 value) => throw new NotImplementedException();
public void Add(KeyValuePair<TKey2, TValue2> item) => throw new NotImplementedException();
public void Clear() => throw new NotImplementedException();
public bool Contains(KeyValuePair<TKey2, TValue2> item) => throw new NotImplementedException();
public bool ContainsKey(TKey2 key) => throw new NotImplementedException();
public void CopyTo(KeyValuePair<TKey2, TValue2>[] array, int arrayIndex) => throw new NotImplementedException();
public IEnumerator<KeyValuePair<TKey2, TValue2>> GetEnumerator() => throw new NotImplementedException();
public bool Remove(TKey2 key) => throw new NotImplementedException();
public bool Remove(KeyValuePair<TKey2, TValue2> item) => throw new NotImplementedException();
public bool TryGetValue(TKey2 key, out TValue2 value) => throw new NotImplementedException();
IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException();
}
然后:
var interfaces = typeof(MyDictionary<string, string>).GetGenericTypeDefinition().GetInterfaces();
var idict1 = interfaces[0];
var idict2 = idict1.GetGenericTypeDefinition();
Console.WriteLine(idict1);
Console.WriteLine(idict2);
结果:
System.Collections.Generic.IDictionary`2[TKey2,TValue2] <-- This is what you get with GetInterfaces()
System.Collections.Generic.IDictionary`2[TKey,TValue] <-- And this is the generic type definition
很明显idict1不可能是IDictionary<,>,因为它是IDictionary<TKey2, TValue2>