将String的值转换为C#中的类型

时间:2012-01-15 09:02:20

标签: c# .net reflection

我有一个包含A类型的String变量 例如:

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 Name我想用一个新的变量 它输入In Runtime)

我能做什么?

4 个答案:

答案 0 :(得分:4)

您可能正在寻找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

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

答案 1 :(得分:1)

我没有使用它,但请尝试Type.GetType("System.Int32");

答案 2 :(得分:0)

您可以使用委托来调用String,Int32和其他构造函数。

答案 3 :(得分:0)

http://www.csharp-examples.net/reflection-examples/

// get type of class Calculator from just loaded assembly Type calcType = testAssembly.GetType("Test.Calculator");