I have some values in an xml file:
...
<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>
...
So when I get effect.Options[0]
, it comes as a string "88"
. I want to cast it to "System.Int32"
. Same with effect.Options[1]
where I want to cast it to "System.Drawing.Color"
.
Something开发者_如何转开发 like:
Converter.Convert value<object> "type"
Any ideas?
If you aren't married to your example XML format, look into XmlSerialization. All those details are taken care of for you on serialization and deserialization - in only a few lines of code.
For Colors:
System.Drawing.ColorConverter colConvert = new ColorConverter();
Color c = (System.Drawing.Color)colConvert.ConvertFromString("#FF00EE");
though I'm not sure what kind of arguments ConvertFromString takes...
Something like:
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;
}
}
switch(Type.GetType(effect.Options[0].ToString()))
{
case typeOf(System.Int32):
int i = (System.Int32)effect.Options[0];
break;
case typeOf(System.Drawing.Color):
System.Drawing.Color color = (System.Drawing.Color)effect.Options[0];
break;
}
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];
}
精彩评论