如何确定类是否继承Dictionary<,>

时间:2015-08-06 12:30:18

标签: c# reflection

我有

public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable

我想检查一个对象是否是SerializeableDictionary(任何泛型类型)。

为此,我尝试了:

type == typeof(SerializableDictionary<,>)
or type.isSubclass()
or typeof(SerializableDictionary<,>).isAssigneableFrom(type)
没什么作用。 如何判断类型是SerializableDictionary还是任何类型?

TNX!

2 个答案:

答案 0 :(得分:2)

var obj = new List<int>(); // new SerializableDictionary<string, int>();
var type = obj.GetType();

var dictType = typeof(SerializableDictionary<,>);
bool b = type.IsGenericType && 
         dictType.GetGenericArguments().Length == type.GetGenericArguments().Length &&
         type == dictType.MakeGenericType(type.GetGenericArguments());

答案 1 :(得分:1)

我可能会创建一个界面ISerializableDictionary,让SerializableDictionary<TKey, TValue>继承该界面。

public interface ISerializableDictionary : IDictionary
{
}

public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable, ISerializableDictionary

然后只是:

var res = dic is ISerializableDictionary;
相关问题