C# - 通过反射获取简单类型的用户友好名称?

时间:2011-01-06 13:48:53

标签: c# reflection types

Type t = typeof(bool);
string typeName = t.Name;

在这个简单示例中,typeName的值为"Boolean"。我想知道是否/如何让它说"bool"

对于int / Int32,double / Double,string / String。

相同

7 个答案:

答案 0 :(得分:39)

using CodeDom;
using Microsoft.CSharp;

// ...

Type t = typeof(bool);

string typeName;
using (var provider = new CSharpCodeProvider())
{
    var typeRef = new CodeTypeReference(t);
    typeName = provider.GetTypeOutput(typeRef);
}

Console.WriteLine(typeName);    // bool

答案 1 :(得分:5)

您所称的“友好名称”是特定于语言的,并不依赖于框架。因此,在框架中包含此信息是没有意义的,MS设计指南要求您使用方法名称等的框架名称(例如ToInt32等)。

答案 2 :(得分:2)

据我了解,boolstringint等只是我们C#开发人员的别名。

编译器处理完一个文件后,不再存在这些文件。

答案 3 :(得分:1)

你不能。这些都是C#特定的关键字。但是你可以很容易地映射它们:

switch (Type.GetTypeCode(t)) {
  case TypeCode.Byte: return "byte";
  case TypeCode.String: return "string";
}

答案 4 :(得分:1)

.net框架本身不了解C#特定关键字。但由于它们只有大约十几种,您只需手动创建一个包含所需名称的表。

这可能是Dictionary<Type,string>

private static Dictionary<Type,string> friendlyNames=new Dictionary<Type,string>();

static MyClass()//static constructor
{
  friendlyNames.Add(typeof(bool),"bool");
  ...
}

public static string GetFriendlyName(Type t)
{
  string name;
  if( friendlyNames.TryGet(t,out name))
    return name;
  else return t.Name;
}

此代码不会将Nullable<T>替换为T?,也不会将泛型转换为C#使用的形式。

答案 5 :(得分:0)

我会说你不能,因为这些名称是特定于C#的,因此如果开发人员想要使用VB.NET,则不会产生相同的结果。

您正在获取CLR类型,这实际上是您希望以后能够重新创建该类型的内容。但是你总是可以写一个名字映射器。

答案 6 :(得分:0)

您可以随时创建一个字典,将C#名称转换为您想要的“友好”名称:

Dictionary<System.Type, string> dict = new Dictionary<System.Type, string>();
dict[typeof(System.Boolean)] = "bool";
dict[typeof(System.string)]  = "string";
// etc...