如何获得类型的别名?

Lou*_*hys 3 .net c# reflection types

是否可以实现像这样的方法

string GetFriendlyName(Type type) { ... }
Run Code Online (Sandbox Code Playgroud)

在.NET中,如果可能,将返回该类型的CLR别名?在这种情况下GetFriendlyName(typeof(Foo))将返回"Foo",但GetFriendlyName(typeof(int))将返回"int"而不是像MemberInfo.Name中的"Int32"

Son*_*nül 6

好吧,我不相信没有办法以程序化的方式去做.你可以使用a dictionary而不是like;

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" }
};
Run Code Online (Sandbox Code Playgroud)

编辑:我找到两个问题来提供答案