为什么我反映的字典类型没有实现IDictionary?

时间:2012-01-20 12:28:21

标签: c# reflection

我正在使用反射和递归进行一些通用对象比较。递归方法在每个步骤中需要一些类型信息,由调用者给出。有一次,我知道下一个属性是Dictionary<T,U>,我想发送正确的类型。我想出了这个:

Type dictionaryType = typeof (IDictionary<,>).MakeGenericType(new [] {keyType.PropertyType, typeof(ValueType)});

keyTypeValueType之前发现的类型。但是,根据IDictionary<KeyType, ValueType>,此类型未实现dictionaryType.GetInterfaces()接口。为什么? 看起来就像它应该......

1 个答案:

答案 0 :(得分:4)

因为类型为IS IDictionary<KeyType, ValueType>GetInterfaces方法仅承诺返回An array of Type objects representing all the interfaces implemented or inherited by the current Type。由于IDictionary<>没有(实际上不能)实现自身,因此返回值合法地是它继承的所有接口。

使用Dictionary<,>作为实现IDictionary<,>的任意类,以下更合适:

Type dictionaryType = typeof (Dictionary<,>).MakeGenericType(new [] {keyType.PropertyType, typeof(ValueType)});