C# – 通过reflection获取简单类型的用户友好名称?
Type t = typeof(bool); string typeName = t.Name;
在这个简单的示例中, typeName
的值为"Boolean"
。 我想知道是否/如何让它说"bool"
而不是。
对于int / Int32,double / Double,string / String也是如此。
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
您称之为“友好名称”是特定于语言的,并不依赖于框架。 因此,在框架中包含此信息没有意义,并且MS设计指南要求您使用方法名称等的框架名称(例如ToInt32
等)。
据我所知, bool
, string
, int
等只是我们C#开发人员的别名。
在编译器处理文件之后,不再存在其他文件。
你不能。 这些都是C#特定的关键字。 但您可以轻松地映射它们:
switch (Type.GetTypeCode(t)) { case TypeCode.Byte: return "byte"; case TypeCode.String: return "string"; }
等等
.net框架本身不了解C#特定关键字。 但由于它们只有大约十几个,您只需手动创建一个包含所需名称的表。
这可以是Dictionary
:
private static Dictionary friendlyNames=new Dictionary(); 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
代替Nullable
T?
并且不会将generics转换为C#使用的forms。
我会说你不能,因为这些名称是特定于C#的,因此如果开发人员想要使用VB.NET,则不会产生相同的结果。
您正在获得CLR类型,这实际上是您希望以后能够重新创建该类型的类型。 但是你总是可以写一个名字映射器。
您总是可以创建一个字典来将C#名称转换为您想要的“友好”名称:
Dictionary dict = new Dictionary(); dict[typeof(System.Boolean)] = "bool"; dict[typeof(System.string)] = "string"; // etc...