AJ.*_*AJ. 19 .net c# 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; }
Run Code Online (Sandbox Code Playgroud)
提前致谢.
Jon*_*eet 50
不 - 只需创建一个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" }
};
Run Code Online (Sandbox Code Playgroud)
Luk*_*keH 28
严格来说,这不使用反射,但您可以使用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
Run Code Online (Sandbox Code Playgroud)
(话虽如此,我认为其他答案表明你只使用从CLR类型到C#别名的映射可能是最好的方法.)
小智 9
如果有人需要带有nullables的字典:
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" },
{ typeof(Nullable<byte>), "byte?" },
{ typeof(Nullable<sbyte>), "sbyte?" },
{ typeof(Nullable<short>), "short?" },
{ typeof(Nullable<ushort>), "ushort?" },
{ typeof(Nullable<int>), "int?" },
{ typeof(Nullable<uint>), "uint?" },
{ typeof(Nullable<long>), "long?" },
{ typeof(Nullable<ulong>), "ulong?" },
{ typeof(Nullable<float>), "float?" },
{ typeof(Nullable<double>), "double?" },
{ typeof(Nullable<decimal>), "decimal?" },
{ typeof(Nullable<bool>), "bool?" },
{ typeof(Nullable<char>), "char?" }
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4748 次 |
| 最近记录: |