c# - 有没有办法通过反射获取类型的别名?

标签 c# .net reflection

我正在编写一个简单的代码生成应用程序来从 DB2 数据库模式构建 POCO。我知道这无关紧要,但我更喜欢使用类型别名而不是实际的系统类型名称(如果它们可用的话),即“int”而不是“Int32”。有没有一种方法可以使用反射来获取类型的别名而不是实际类型?

//Get the type name
var typeName = column.DataType.Name;

//If column.DataType is, say, Int64, I would like the resulting property generated
//in the POCO to be...

public long LongColumn { get; set; }

//rather than what I get now using the System.Reflection.MemberInfo.Name property:

public Int64 LongColumn { get; set; }

最佳答案

不 - 只需创建一个 Dictionary<Type,string>将所有类型映射到它们的别名。这是一个固定的集合,所以不难做到:

private static readonly Dictionary<Type, string> Aliases =
    new Dictionary<Type, string>()
{
    { 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(object), "object" },
    { typeof(bool), "bool" },
    { typeof(char), "char" },
    { typeof(string), "string" },
    { typeof(void), "void" }
};

关于c# - 有没有办法通过反射获取类型的别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1362884/

相关文章:

c# - 使用 LINQ 和 mysqlconnection 遇到 fatal error

c# - 当指定级联删除时, Entity Framework 无法加载外键数组属性

c# - 为什么 IProgress<T> Report(T) 方法会阻塞 UI 线程?

java - 如果一个类是最终的,我如何判断使用反射

c# - 使 Visual Studios "Add Service Reference"功能使用现有类

c# - 如何为从组合框中选择的项目声明一个 c# 变量

c# - 最大化/最小化外部应用程序

.net - .NET 的 BBCode 或 wiki 标记库?

java - 如何使用反射来调用以字符串数组作为参数的私有(private)方法

c# - 为什么 Assembly.GetType() 找不到我的类(class)?