我有一个输入字符串,可以是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;
}
}
您可以使用'switch'语句。 – Alex
你能否提供一段真正编译的代码,并用英文解释你想要这段代码做什么?你还可以展示你应该如何调用它并使用返回值?无论如何,请查看[static'Convert' class](https://msdn.microsoft.com/en-us/library/system.convert(v = vs.110).aspx)。 – CodeCaster
因此,用户输入的类型和值(当然都是字符串),并且您想要一个具有该值的类型的变量? – David