c# – 检查泛型类型
发布时间:2020-12-15 19:48:36 所属栏目:百科 来源:网络整理
导读:我想检查泛型变量是否属于某种类型,但不想检查通用部分. 假设我有一个List int的变量.和另一个List double.我只想检查它是否为List类型 if(variable is List) {} 并不是 if (variable is Listint || variable is Listdouble) {} 这可能吗? 谢谢 解决方法 va
我想检查泛型变量是否属于某种类型,但不想检查通用部分.
假设我有一个List< int>的变量.和另一个List< double>.我只想检查它是否为List<>类型 if(variable is List) {} 并不是 if (variable is List<int> || variable is List<double>) {} 这可能吗? 谢谢 解决方法variable.GetType().IsGenericType && variable.GetType().GetGenericTypeDefinition() == typeof(List<>) 当然,这仅在变量属于List< T>类型时有效,并且不是派生类.如果你想检查它是否是List< T>或者从它继承,你应该遍历继承层次结构并检查每个基类的上述语句: static bool IsList(object obj) { Type t = obj.GetType(); do { if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>)) return true; t = t.BaseType; } while (t != null); return false; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |