检查对象是否为C#中的非特定泛型类型 [英] Check if object is of non-specific generic type in C#
本文介绍了检查对象是否为C#中的非特定泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下课程:
public class General<T> { }
我想找出一个对象是否属于该类型.
我知道我可以使用反射来确定对象是否具有Type.GetGenericTypeDefinition
的通用类型,但是我想避免这种情况.
And I want to find out if an object is of that type.
I know I can use reflection to find out whether the object is of that generic type with Type.GetGenericTypeDefinition
, but I want to avoid that.
是否可以做类似obj is General<T>
或obj.GetType().IsAssignableFrom(typeof(General<T>))
的事情?
Is it possible to do something like obj is General<T>
, or obj.GetType().IsAssignableFrom(typeof(General<T>))
?
尽管我可能在搜索中使用了错误的关键字,但我找不到类似的问题,这让我感到很惊讶.
I'm quite surprised that I couldn't find a similar question, although I may have used wrong keywords in my searches.
推荐答案
您可以执行以下操作:
var obj = new General<int>();
var type = obj.GetType();
var isGeneral =
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(General<>)) ||
type.GetBaseTypes().Any(x => x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(General<>));
GetBaseTypes
是以下扩展方法:
public static IEnumerable<Type> GetBaseTypes(this Type type)
{
if (type.BaseType == null) return type.GetInterfaces();
return new []{type}.Concat(
Enumerable.Repeat(type.BaseType, 1)
.Concat(type.GetInterfaces())
.Concat(type.GetInterfaces().SelectMany<Type, Type>(GetBaseTypes))
.Concat(type.BaseType.GetBaseTypes()));
}
要获得闲置答案的信用额
这篇关于检查对象是否为C#中的非特定泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文