Pra*_*eek 2 .net c# reflection types
是否有一个函数,给定一个C#类型的字符串表示,返回相应的.Net类型或.Net类型的字符串表示; 或以任何方式实现这一目标.
例如 :
"bool" - > System.Boolean或"System.Boolean"
"int" - > System.Int32或"System.Int32"
...
谢谢.
编辑:非常抱歉,它不是我希望的"类型到类型"映射,而是"字符串到字符串"映射或"字符串到类型"映射.
该名单内置类型在C#是很短,不太可能发生变化,所以我觉得有一本字典或一个大的switch语句来映射这些不应该是难以维持.
如果你想支持可空类型,我相信你没有别的选择来解析输入字符串:
static Type GetTypeFromNullableAlias(string name)
{
if (name.EndsWith("?"))
return typeof(Nullable<>).MakeGenericType(
GetTypeFromAlias(name.Substring(0, name.Length - 1)));
else
return GetTypeFromAlias(name);
}
static Type GetTypeFromAlias(string name)
{
switch (name)
{
case "bool": return typeof(System.Boolean);
case "byte": return typeof(System.Byte);
case "sbyte": return typeof(System.SByte);
case "char": return typeof(System.Char);
case "decimal": return typeof(System.Decimal);
case "double": return typeof(System.Double);
case "float": return typeof(System.Single);
case "int": return typeof(System.Int32);
case "uint": return typeof(System.UInt32);
case "long": return typeof(System.Int64);
case "ulong": return typeof(System.UInt64);
case "object": return typeof(System.Object);
case "short": return typeof(System.Int16);
case "ushort": return typeof(System.UInt16);
case "string": return typeof(System.String);
default: throw new ArgumentException();
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
GetTypeFromNullableAlias("int?").Equals(typeof(int?)); // true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1776 次 |
| 最近记录: |