简体   繁体   中英

How to determine if class inherits Dictionary<,>

I have

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

And I want to check if an object is SerializeableDictionary (of any generic types).

For that I tried:

type == typeof(SerializableDictionary<,>)
or type.isSubclass()
or typeof(SerializableDictionary<,>).isAssigneableFrom(type)

nothing works. How can I tell if the type is SerializableDictionary or any type?

tnx!

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());

I would probably create an interface ISerializableDictionary and let SerializableDictionary<TKey, TValue> inherit from that.

public interface ISerializableDictionary : IDictionary
{
}

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

Then just:

var res = dic is ISerializableDictionary;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM