遵循此链接:使用 C# 将 xml 反序列化为超类对象
我已经实现:
xml文件
<?xml version="1.0" encoding="utf-8" ?>
<xPlugins>
<xPlugin>
<Multiple>
<Operator>
<Add>
<Operator>1</Operator>
<Operator>2</Operator>
</Add>
</Operator>
<Operator>
<Add>
<Operator>3</Operator>
<Operator>4</Operator>
</Add>
</Operator>
</Multiple>
</xPlugin>
</xPlugins>
班级
public abstract class Calculator
{
public Calculator() { }
public virtual int Calculate()
{
return 0;
}
}
public class Operator : Calculator
{
public int value { get; set; }
public Operator() { }
public Operator(string name)
{
}
public override int Calculate()
{
return value;
}
}
public class Add : Calculator
{
public List<Calculator> calculators { get; set; }
public Add() { }
public Add(List<Calculator> calculators)
{
this.calculators = calculators;
}
public override int Calculate()
{
List<int> value = new List<int>();
foreach (Calculator calculator in calculators)
{
value.Add(calculator.Calculate());
}
return value.Sum();
}
}
public class Minus : Calculator
{
public List<Calculator> calculators { get; set; }
public Minus() { }
public Minus(List<Calculator> calculators)
{
this.calculators = calculators;
}
public override int Calculate()
{
int value = calculators[0].Calculate();
for (int i = 1; i < calculators.Count; i++)
{
value -= calculators[i].Calculate();
}
return value;
}
}
public class divide: Calculator
{
public List<Calculator> calculators { get; set; }
public Divide() { }
public Divide(List<Calculator> calculators)
{
this.calculators = calculators;
}
public override int Calculate()
{
int value = calculators[0].Calculate();
for (int i = 1; i < calculators.Count; i++)
{
value /= calculators[i].Calculate();
}
return value;
}
}
public class Multiple : Calculator
{
public List<Calculator> calculators { get; set; }
public Multiple() { }
public Multiple(List<Calculator> calculators)
{
this.calculators = calculators;
}
public override int Calculate()
{
int value = calculators[0].Calculate();
for (int i = 1; i < calculators.Count; i++)
{
value *= calculators[i].Calculate();
}
return value;
}
}
public class xPlugin
{
public Calculator calculator { get; set; }
}
public class xPlugins
{
[XmlElement("xPlugin", typeof(xPlugin))]
public xPlugin[] Plugin { get; set; }
}
XML序列化器定义:
public static void getObject(ref xPlugins plugins)
{
try
{
List<Type> type = new List<Type>();
type.Add(typeof(Add));
type.Add(typeof(Minus));
type.Add(typeof(Multiple));
type.Add(typeof(Subtract));
type.Add(typeof(Operator));
XmlSerializer xml = new XmlSerializer(typeof(xPlugins), type.ToArray());
FileStream fs = new FileStream("test.xml", FileMode.Open);
plugins = (xPlugins)xml.Deserialize(fs);
}
catch (Exception ex)
{
throw;
}
}
使用:
private void button1_Click(object sender, EventArgs e)
{
readXML.getObject(ref this.plugins);
foreach (xPlugin plugin in plugins.Plugin)
{
plugin.calculator.Calculate();
}
}
反序列化进程成功反序列化xPlugins
并xPlugin
进入其关联类,但未能将add
, multiple
, divide
,反序列化divide
为其基类Calculator
。xPlugin
的calculator
属性总是得到空值。那么我怎样才能将这些元素反序列化为其基类呢?