C# 检查两个泛型类型是否相等
我需要找出一个类型是否是某种泛型类型C# 检查两个泛型类型是否相等,c#,generics,types,C#,Generics,Types,我需要找出一个类型是否是某种泛型类型 class MyType<T> {} var instance = new MyType<int>(); var type = instance.GetType(); 这确实管用,但感觉脏。它也可能是错误的,因为它不是全名 type.Name == typeof( MyType<> ).Name type.Name==typeof(MyType).Name 我想有办法做到这一点,但我还没有找到。使用IsAssigna
class MyType<T> {}
var instance = new MyType<int>();
var type = instance.GetType();
这确实管用,但感觉脏。它也可能是错误的,因为它不是全名
type.Name == typeof( MyType<> ).Name
type.Name==typeof(MyType).Name
我想有办法做到这一点,但我还没有找到。使用IsAssignableFrom
将不起作用,因为我需要知道当前类型,而不是它的父类型是否相等。如果对象的具体类型是MyType
,这将起作用。它不适用于从MyType
派生的类型实例,如果MyType
是接口类型,它也不适用
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(MyType<>))
if(type.IsGenericType
&&type.GetGenericTypeDefinition()==typeof(MyType))
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(MyType<>))