如何获得类型的别名

本文关键字:别名 类型 何获得 | 更新日期: 2023-09-27 18:04:19

是否可以实现像

这样的方法?
string GetFriendlyName(Type type) { ... }
如果可能的话,.NET中的

将返回该类型的CLR别名。在这种情况下,GetFriendlyName(typeof(Foo))将返回"Foo",但GetFriendlyName(typeof(int))将返回"int"而不是像MemberInfo中的"Int32"。名称

如何获得类型的别名

好吧,我不相信没有办法通过编程来实现。你可以用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" }
};

EDIT:我找到了两个问题来提供答案

  • 是否有一种方法可以通过反射获得类型别名?
  • 可以在c#中获得别名类型的类型吗?

您可以这样尝试:

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,以提高性能。