c# - 将字符串的值转换为 C# 中的类型

标签 c# .net reflection

我有一个包含 A 类型的字符串变量 例如:

String StrType ="Int32"; // Or "Decimal" Or Char Or an Enum Color

我想创建一个类型为 StrType 的新变量(StrType 的值)

在这个例子中我想要这个变量:

Int32 MyType;

我不想使用 swich 或 if...else 来检测类型,因为 不是这个 -->

If (StrType=="Int32")
   Int32 MyType;

(换句话说,我在 StrType 中有一个类型名称,我想用它创建一个新变量 它在运行时输入)

我能做什么?

最佳答案

您可能正在寻找 Type.GetType(StrType) - 这将为您提供一个包含相应类型的 Type 变量。如果您想获取 StrType 的对象实例,则需要使用一些反射,如下所示:

    var t = Type.GetType("System.Int32");
    var constructor = t.GetConstructor(Type.EmptyTypes);
    object intObject = constructor.Invoke(null); //intObject will have type System.Int32

当然,这只有在类型被成功解析并且该类型存在无参数构造函数时才有效。在生产中,您应该为此添加检查。

关于c# - 将字符串的值转换为 C# 中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868597/

相关文章:

c# - TabPage 作为用户控件?

java - 反射和数组

c# - 在 MulticastDelegate 上调用 BeginInvoke?

c# - 如何通过反射获取字符串属性的值?

java泛型和反射,为什么结果不同

c# - 如何根据复选框值验证文本框

c# - 批量插入的 LINQ-to-SQL 性能问题

C# 抽象类 : Cannot implicitly convert type type1 to type2

c# - this == null 怎么可能?

c# - silverlight Match TimeoutInMilliseconds 错误 : resolve DomainServiceClientCodeGenerator