我有一個輸入字符串,可以是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