如何判断类是否继承Dictionary<,> [英] How to determine if class inherits Dictionary<,>

查看:46
本文介绍了如何判断类是否继承Dictionary<,>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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

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

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

为此我尝试过:

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

没有任何效果.如何判断类型是 SerializableDictionary 还是任何类型?

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

这篇关于如何判断类是否继承Dictionary&lt;,&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆