[英]How to determine if class inherits Dictionary<,>
我有
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
而且我想检查对象是否为SerializeableDictionary(任何通用类型)。
为此,我尝试:
type == typeof(SerializableDictionary<,>)
or type.isSubclass()
or typeof(SerializableDictionary<,>).isAssigneableFrom(type)
没有任何效果。 如何判断类型是SerializableDictionary还是任何类型?
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());
我可能会创建一个接口ISerializableDictionary
并让SerializableDictionary<TKey, TValue>
继承自该接口。
public interface ISerializableDictionary : IDictionary
{
}
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable, ISerializableDictionary
然后:
var res = dic is ISerializableDictionary;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.