c# - 通过反射获取某个C#类型的.Net对应类型

标签 c# .net reflection types

是否有一个函数,给定一个 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/

相关文章:

c# - 如何在 Windows Phone 8 中设置背景图像?

c# - ASP.NET Core MVC 中缺少类型/命名空间

c# - 在 Metro 风格应用程序中使用遗留程序集

.net - 基于两个参数对元素进行分组

c# - .NET 中的 ElapsedTime 格式

c++ - 我怎样才能实现一个函数来调用任何(任意)函数及其(任意)参数?

c# - Paypal API 证书

c# - 系统关闭/重启时的 Windows 服务日志写入

Java反射类

java - 你如何让java方法注释在scala中工作