2016-02-09 23 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; 
    }; 
} 
相關問題