Get type name without any generics info

后端 未结 3 2046
清酒与你
清酒与你 2021-01-07 17:25

If I write:

var type = typeof(List);
Console.WriteLine(type.Name);

It will write:

List`1

3条回答
  •  自闭症患者
    2021-01-07 18:18

    No, it makes perfect sense for it to include the generic arity in the name - because it's part of what makes the name unique (along with assembly and namespace, of course).

    Put it this way: System.Nullable and System.Nullable are very different types. It's not expected that you'd want to confuse the two... so if you want to lose information, you're going to have to work to do it. It's not very hard, of course, and can be put in a helper method:

    public static string GetNameWithoutGenericArity(this Type t)
    {
        string name = t.Name;
        int index = name.IndexOf('`');
        return index == -1 ? name : name.Substring(0, index);
    }
    

    Then:

    var type = typeof(List);
    Console.WriteLine(type.GetNameWithoutGenericArity());
    

提交回复
热议问题