是否有一个函数,给定一个 C# 类型的字符串表示,返回相应的 .Net 类型或 .Net 类型的字符串表示?或任何实现此目的的方法。
例如:
“ bool ”-> System.Boolean 或“System.Boolean”
“int”->System.Int32 或“System.Int32”
...
谢谢。
编辑:真的很抱歉,这不是我想要的“类型到类型”映射,而是“字符串到字符串”映射或“字符串到类型”映射。
最佳答案
list of built-in types in 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();
}
}
测试:
GetTypeFromNullableAlias("int?").Equals(typeof(int?)); // true
关于c# - 通过反射获取某个C#类型的.Net对应类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1459954/