[英]Check if two generic types are equal
I need to find if a type is a certain generic type. 我需要找到一个类型是否是某种泛型类型。
class MyType<T> {}
var instance = new MyType<int>();
var type = instance.GetType();
This check does not work, but this is what I want to check. 此检查不起作用,但这是我想要检查的。 If the type is of that generic type, regardless of what
T
is. 如果类型是该泛型类型,则无论
T
是什么。
type == typeof( MyType<> )
This does work, but feels dirty. 这确实有效,但感觉很脏。 It could also be wrong since it's not the
FullName
. 它也可能是错误的,因为它不是
FullName
。
type.Name == typeof( MyType<> ).Name
I'm assuming there is a way to do this, but I haven't found one. 我假设有办法做到这一点,但我还没找到。 Using
IsAssignableFrom
will not work, because I need to know if the current type, and not one of it's parents, are equal. 使用
IsAssignableFrom
行不通的,因为我需要知道当前的类型,而不是它的父类之一是否相等。
This will work if the concrete type of the object is MyType<T>
. 如果对象的具体类型是
MyType<T>
这将起作用。 It will not work for instances of types derived from MyType<T>
, and will not work if MyType<T>
is an interface type. 它不适用于从
MyType<T>
派生的类型的实例,如果MyType<T>
是接口类型,则不起作用。
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(MyType<>))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.