2011-03-02 12 views
0

我有一個XML文件中的一些值:如何將字符串轉換爲類型信息以「System.Int32」,「System.Color」等形式存儲的任何類型?

... 
<Effect> 
    <Type>Blur</Type> 
    <Options> 
    <Option Type="System.Int32">88</Option> 
    <Option Type="System.Drawing.Color">Color [A=0, R=1, G=2, B=3]</Option> 
    </Options> 
</Effect> 
... 

所以,當我得到effect.Options[0],它作爲一個字符串"88"。我想將它投射到"System.Int32"。與effect.Options[1]相同,我想將它投射到"System.Drawing.Color"

喜歡的東西:

Converter.Convert value<object> "type" 

任何想法?

回答

-1

開關(Type.GetType(effect.Options [0]的ToString())) { 情況下的typeof(System.Int32): INT I =(System.Int32)effect.Options [0]; 休息; case typeOf(System.Drawing.Color): System.Drawing.Color color =(System.Drawing.Color)effect.Options [0]; 休息; }

if(effect.Options[0].Attributes["Type"].Value.ToString()) == "System.Int32" /*pseudo code here in this part, just showing that you need to get the type from the XML as an attribute or whatever*/) 
{ 
    int i = (System.Int32)effect.Options[0]; 
} 
else if(effect.Options[0].Attributes["Type"].Value.ToString()) == "System.Drawing.Color"/*pseudo code here in this part, just showing that you need to get the type from the XML as an attribute or whatever*/) 
{ 
    System.Drawing.Color color = (System.Drawing.Color)effect.Options[0]; 
} 
+0

謝謝,在這種情況下,case語句將使用字符串值?你是怎麼從琴絃中得到這些的?我也必須使用開關嗎?就是想。最後一件事,你可以將顏色字符串轉換爲Color嗎?它會起作用嗎? – 2011-03-02 01:04:33

+2

它不會工作。 C#不支持帶有類型的switch語句。 – Lloyd 2011-03-02 01:05:23

+0

仍然無法正常工作。你不能只是添加一個演員,並期望轉換神奇地工作。 – 2011-03-02 01:11:19

2

如果你不嫁給你的示例XML格式,看看XmlSerialization。所有這些細節都在您的序列化和反序列化中處理 - 僅需幾行代碼。

1

對於顏色:

System.Drawing.ColorConverter colConvert = new ColorConverter(); 
Color c = (System.Drawing.Color)colConvert.ConvertFromString("#FF00EE"); 

,雖然我不知道ConvertFromString需要什麼樣的參數...


喜歡的東西:

string sType = "System.Int32";//Get your type from attribute 
    string value = "88"; //Get your element 

    switch (sType) 
    { 
     case "System.Int32": 
      int i = (int)Convert.ChangeType(value, Type.GetType("System.Int32"), CultureInfo.InvariantCulture); 
      break; 
     case "System.Drawing.Color" : 
      Color c = (Color)Convert.ChangeType(value, Type.GetType("System.Drawing.Color"), CultureInfo.InvariantCulture); 
      break; 
    } 

OR

for (int i = 0; i < effect.Options.Count; i++) 
{ 
    object oResult = Convert.ChangeType(effect.Options[i], Type.GetType(effect.Options[i].Attributes["Type"].Value.ToString()), CultureInfo.InvariantCulture); 
    if (oResult is int) 
    { 
     //Process as int 
     int iTmp = (int)oResult; 
    } 
    else if (oResult is Color) 
    { 
     //process as color 
     Color cTmp = (Color)oResult; 
    } 
} 
+1

'Convert.ChangeType'不能轉換爲顏色。它會拋出「從'System.String'無效轉換爲'System.Drawing.Color'。」 – 2011-03-02 01:33:32

相關問題