2016-02-09 21 views
0

我有一个输入字符串,可以是int,string,float或任何数据类型。如何从字符串创建一个类型并在运行时解析

现在我想要做一些事情,如:

string stringType= "Int"; 
Type dataType = Type.GetType(stringType); 

string someValue = 20; 

int newValue = (dataType)someValue ; 

编辑:

我将获得这两个类型和值作为字符串,需要转换它们的运行时间。

public void StoreWorkData(List<TypeAndvalue> workDataPropertyDetails) 
     { 
      foreach (var property in workDataPropertyDetails) 
      { 
       string stringType = property.dataType; 
       //Want to create the type in run time  
       Type dataType = Type.GetType(stringType); 

       //Assign the value to type created above  
       dataType newValue = (dataType)property.Value; 
      } 
     } 
+0

您可以使用'switch'语句。 – Alex

+1

你能否提供一段真正编译的代码,并用英文解释你想要这段代码做什么?你还可以展示你应该如何调用它并使用返回值?无论如何,请查看[static'Convert' class](https://msdn.microsoft.com/en-us/library/system.convert(v = vs.110).aspx)。 – CodeCaster

+0

因此,用户输入的类型和值(当然都是字符串),并且您想要一个具有该值的类型的变量? – David

回答

3

好吧,首先我们创建了一个方法来解析字符串对象:

static object Parse(string typeName, string value) 
{ 
    var type = Type.GetType(typeName); 
    var converter = TypeDescriptor.GetConverter(type); 

    if (converter.CanConvertFrom(typeof(string))) 
    { 
     return converter.ConvertFromInvariantString(value); 
    } 

    return null; 
} 

里面你后你可以把它叫做方法:

public void StoreWorkData(List<TypeAndvalue> workDataPropertyDetails) 
{ 
    foreach (var property in workDataPropertyDetails) 
    { 
     dynamic newValue = Parse(property.dataType, property.Value); 

     SomeMethod(newValue); 
    } 
} 

您可以有不同的方法SomeMethod不同的参数类型:

void SomeMethod(int value); 
void SomeMethod(double value); 
... 

动态类型做魔术调用正确的方法(如果存在的话)。 欲了解更多信息,请看看this

2

Type.GetTypeused correctly,会给你一个Type例如其本身可用于通过类似Activator.CreateInstance创建该类型的实例。

string desiredTypeName = /* get the type name from the user, file, whatever */ 
Type desiredType = Type.GetType(desiredTypeName); 
object instance = Activator.CreateInstance(desiredType); 

如果desiredTypeName是 “System.String”,然后instance将是一个string。如果它是“YourNamespace.YourType”,那么instance将是YourType。等等。

如果您需要使用参数there are overloads of CreateInstance that allow you to specify constructor parameters构造实例。

如果你的构造函数参数的值也给你们的字符串,可以使用Type对象的方法对desiredType实例get the available constructors,并确定其所需的参数类型和解析字符串转换为这些类型。


注意,此方法会限制你使用的System.Object接口为instance在编译时;自然,你将不能编写自然地以实例访问实例的代码作为运行时类型,因为直到运行时才知道该类型。如果你愿意的话,你可以打开类型名称并向下倾倒instance,但是在那时你做了一堆工作(所有这些都是垃圾),因为没有任何效果。

另请注意,Activator不是最快方式来创建在运行时确定类型的实例;这只是最简单的。

1

活化剂。的CreateInstance可用于在运行时创建类的实例

string stringType= "MyType"; 
Type dataType = Type.GetType(stringType); 
dynammic instance = Activator.CreateInstance(dataType); 

从字符串支持铸造你必须实现以下方法在你的类型

public static explicit operator MyType(string s) 
{ 
    // put logic to convert string value to your type 
    return new MyType 
    { 
     value = s; 
    }; 
} 
相关问题