我正在编写一个简单的代码生成应用程序来从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
将所有类型映射到其别名.这是一个固定的集合,因此不难做到:
private static readonly DictionaryAliases = new Dictionary () { { 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" } };
严格来说,这不使用反射,但您可以使用CodeDOM来获取类型的别名:
Type t = column.DataType; // Int64 string typeName; using (var provider = new CSharpCodeProvider()) { var typeRef = new CodeTypeReference(t); typeName = provider.GetTypeOutput(typeRef); } Console.WriteLine(typeName); // long
(话虽如此,我认为其他答案表明你只使用从CLR类型到C#别名的映射可能是最好的方法.)
如果有人需要带有nullables的字典:
private static readonly DictionaryAliases = new Dictionary () { { 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" }, { typeof(Nullable ), "byte?" }, { typeof(Nullable ), "sbyte?" }, { typeof(Nullable ), "short?" }, { typeof(Nullable ), "ushort?" }, { typeof(Nullable ), "int?" }, { typeof(Nullable ), "uint?" }, { typeof(Nullable ), "long?" }, { typeof(Nullable ), "ulong?" }, { typeof(Nullable ), "float?" }, { typeof(Nullable ), "double?" }, { typeof(Nullable ), "decimal?" }, { typeof(Nullable ), "bool?" }, { typeof(Nullable ), "char?" } };