获取类型的名称没有任何泛型信息 [英] Get type name without any generics info

查看:102
本文介绍了获取类型的名称没有任何泛型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写的:

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

这会写:

List`1

我希望它只是写:

列表

我怎样才能做到这一点?
是有一个更聪明的办法做到这一点,而不必使用子串或类似的字符串处理函数?

How can I do that? Is there a smarter way to do it without having to use Substring or similar string manipulation functions?

推荐答案

没有,它非常有意义为它在名称中包含通用的元数 - 因为它是什么使(当然与装配和命名空间一起)的名称独特之处

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).

这样说吧: System.Nullable 系统.Nullable< T> 是非常不同的类型。这不是预计你会希望把两者混淆...因此,如果你的希望的丢失信息,你将必须努力做到这一点。这是不是很辛苦,当然,可以放在一个辅助方法:

Put it this way: System.Nullable and System.Nullable<T> 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<string>);
Console.WriteLine(type.GetNameWithoutGenericArity());

这篇关于获取类型的名称没有任何泛型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆