Check if two generic types are equal

微笑、不失礼 提交于 2021-02-18 22:31:28

问题


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.

type == typeof( MyType<> )

This does work, but feels dirty. It could also be wrong since it's not the 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.


回答1:


This will work if the concrete type of the object is 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.

if (type.IsGenericType
    && type.GetGenericTypeDefinition() == typeof(MyType<>))


来源:https://stackoverflow.com/questions/16329590/check-if-two-generic-types-are-equal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!