我在xml文件中有一些值:
...
<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"
有什么想法吗?
答案 0 :(得分:2)
如果您未与示例XML格式结合,请查看XmlSerialization。所有这些细节都会在序列化和反序列化中得到解决 - 只需几行代码即可。
答案 1 :(得分: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;
}
或强>
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;
}
}
答案 2 :(得分:-1)
开关(Type.GetType(effect.Options [0] .ToString()))
{
case 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];
}