How do you get the name of a generic class using reflection?

半城伤御伤魂 提交于 2021-02-07 09:59:45

问题


How do you get the name of a generic class using reflection

eg

public class SomeGenericClass<T>
{
}

SomeGenericClass<int> test = new SomeGenericClass<int>();

test.GetType().Name returns "SomeGenericClass'1"

How do I get it to return "SomeGenericClass" without the '1?


回答1:


How about just the following?

test.GetType().Name.Split('\'')[0]

It works on non-generic classes too.




回答2:


The '1 is part of the name, because, for example, List<T> and List (if I created such a class) are different classes.

'1 means that it has one type parameter. If you want to know the type of that parameter, use test.GetType().GetGenericArguments()[0];




回答3:


enum.GetName(test.GetType(), test).ToString()


来源:https://stackoverflow.com/questions/1752823/how-do-you-get-the-name-of-a-generic-class-using-reflection

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