Get user-friendly name of simple types through reflection?
Type t = typeof(bool);
string typeName = t.Name;
In this simple example, typeName
would have the value "Boolean"
. I'd like to know if/how I can get it to say "bo开发者_StackOverflow中文版ol"
instead.
Same for 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
The "friendly names" as you call them are language-specific and not tied to the framework. Therefore, it doesn't make sense to have this information in the framework, and the MS design guidelines require you to use the framework names for method names etc. (such as ToInt32
etc.).
From what I understand, bool
, string
, int
, etc. are just aliases for us C# developers.
After the compiler processes a file, no more of them are acutally present.
you can't. Those are all C# specific keywords. But you can easily map them:
switch (Type.GetTypeCode(t)) {
case TypeCode.Byte: return "byte";
case TypeCode.String: return "string";
}
etc
You could always create a dictionary to translate the C# names to the "friendly" ones you want:
Dictionary<System.Type, string> dict = new Dictionary<System.Type, string>();
dict[typeof(System.Boolean)] = "bool";
dict[typeof(System.string)] = "string";
// etc...
The .net framework itself doesn't know about C# specific keywords. But since there are only about a dozen of them, you can simply manually create a table containing the names you want.
This could be a 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;
}
This code doesn't replace Nullable<T>
with T?
and doesn't transform generics into the form C# uses.
I'd say you can't since those names are specific to C# and as such will not produce the same result if the developer wanted to use VB.NET.
You are getting the CLR type and that is really what you would want to be able to recreate the type later. But you can always write a name mapper.
精彩评论