C#如何从反射得到的Type对象中检索int等原始类型的友好别名?
问题解答
没有原生的内置API可以直接从Type对象中检索到C#专属的类型别名。
这类别名是C#语言层面的语法定义,不属于.NET运行时的公共属性:同一个CLR类型在不同.NET语言中的别名存在差异,比如Int32在VB.NET中的别名是Integer,在F#中的别名是int,因此运行时的Type实例本身不会存储某一门语言的专属别名信息。
你可以通过字典映射的方式封装统一的获取逻辑,比逐个添加显式判断的可维护性更高,参考实现如下:
using System; using System.Collections.Generic; public static class TypeAliasExtensions { // 预先映射所有C#内置类型和对应的别名 private static readonly Dictionary<Type, string> _csharpAliasMap = new Dictionary<Type, string> { { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(sbyte), "sbyte" }, { typeof(short), "short" }, { typeof(ushort), "ushort" }, { typeof(int), "int" }, { typeof(uint), "uint" }, { typeof(long), "long" }, { typeof(ulong), "ulong" }, { typeof(float), "float" }, { typeof(double), "double" }, { typeof(decimal), "decimal" }, { typeof(char), "char" }, { typeof(string), "string" }, { typeof(object), "object" }, { typeof(void), "void" } }; public static string GetCSharpTypeAlias(this Type type) { // 匹配到别名直接返回,未匹配返回原类型名 if (_csharpAliasMap.TryGetValue(type, out string alias)) { return alias; } // 可选:处理可空值类型的别名,比如int? if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type underlyingType = Nullable.GetUnderlyingType(type); return $"{underlyingType.GetCSharpTypeAlias()}?"; } return type.Name; } }
使用示例:
// 输出:int Console.WriteLine(typeof(int).GetCSharpTypeAlias()); // 输出:byte Console.WriteLine(typeof(byte).GetCSharpTypeAlias()); // 输出:int? Console.WriteLine(typeof(int?).GetCSharpTypeAlias()); // 无别名的自定义类型返回原名称,比如输出:MyCustomClass Console.WriteLine(typeof(MyCustomClass).GetCSharpTypeAlias());
内容的提问来源于stack exchange,提问作者Seva Alekseyev
相关产品推荐
相关产品推荐

