如何获得类型的别名?

时间:2013-03-18 07:04:08

标签: c# .net reflection types

是否可以实现类似

的方法
string GetFriendlyName(Type type) { ... }
如果可能,在.NET中

将返回该类型的CLR alias?在这种情况下,GetFriendlyName(typeof(Foo))将返回“Foo”,但GetFriendlyName(typeof(int))将返回“int”而非MemberInfo.Name中的“Int32”

2 个答案:

答案 0 :(得分:6)

,我不认为没有办法以编程方式进行。您可以使用dictionary代替赞;

public static readonly Dictionary<Type, string> aliases = new Dictionary<Type, string>()
{
    { typeof(string), "string" },
    { typeof(int), "int" },
    { typeof(byte), "byte" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(ushort), "ushort" },
    { typeof(long), "long" },
    { typeof(uint), "uint" },
    { typeof(ulong), "ulong" },
    { typeof(float), "float" },
    { typeof(double), "double" },
    { typeof(decimal), "decimal" },
    { typeof(object), "object" },
    { typeof(bool), "bool" },
    { typeof(char), "char" }
};

编辑:我发现了两个问题来提供答案

答案 1 :(得分:3)

您可以尝试这种方式:

private string GetFriendlyName(Type type)
{
    Dictionary<string, string> alias = new Dictionary<string, string>()
        {
            {typeof (byte).Name, "byte"},
            {typeof (sbyte).Name, "sbyte"},
            {typeof (short).Name, "short"},
            {typeof (ushort).Name, "ushort"},
            {typeof (int).Name, "int"},
            {typeof (uint).Name, "uint"},
            {typeof (long).Name, "long"},
            {typeof (ulong).Name, "ulong"},
            {typeof (float).Name, "float"},
            {typeof (double).Name, "double"},
            {typeof (decimal).Name, "decimal"},
            {typeof (object).Name, "object"},
            {typeof (bool).Name, "bool"},
            {typeof (char).Name, "char"},
            {typeof (string).Name, "string"}
        };
    return alias.ContainsKey(type.Name) ? alias[type.Name] : type.Name;
}

我建议您提供alias字典static readonly以获得性能优势。