Deserialize xml into super class object with C#

本秂侑毒 提交于 2019-12-05 05:17:23
Yaniv

I am guessing you want to use XmlSerializer. If you need a "polymorphic" deserialization you can pass a list of types that the serializer should know about (this works if they all inherit from the same base class but not from interface).

Example:

List<Type> extraTypes = new List<Type>();
extraTypes.Add(typeof(multiple));
extraTypes.Add(typeof(add));
extraTypes.Add(typeof(substract));
extraTypes.Add(typeof(divide));
var ser = new XmlSerializer(typeof(Foo), extraTypes.ToArray());

It's explained here: Serializing and restoring an unknown class

But there is another problem that in your XML your operand can hold two different types: an operation or an parameter (a, b, c, d) and you cannot represent it in your class.

Something that I usually see is this (I implemented only the add operation, and I am assuming the expression is numeric):

public class Expression
{
  public virtual int Evaluate()
  {
  }
}

public class Add : Expression
{
  Expression _left;
  Expression _right;

  public Add(Expression left, Expression right)
  {
    _left = left;
    _right = right;
  }

  override int Evalute()
  {
    return _left.Evalute() + _right.Evalute();
  }
}

public class Parameter : Expression
{
  public int Value{get;set;}

  public Parameter(string name)
  {
    // Use the name however you need.
  }

  override int Evalute()
  {
    return Value;
  }
}

This way you have only one base class so everything is simpler. If that make sense I guess it won't be hard to deserialize it.

EDIT: If the base class is Calculator (instead of Expression) the XML will look like this:

<Calculator xsi:type="Multiple">
  <calculators>
    <Calculator xsi:type="Add">
      <calculators>
        <Calculator xsi:type="Operator">
          <value>12</value>
        </Calculator>
      </calculators>
    </Calculator>
  </calculators>
</Calculator>

I have created a simple calculator object and serialized it and that's what I got. If you will deserialize it you will get a calculator that will return 12.

Maybe you can use XmlAttributes to change the names of the elements in the XML or in the worst case write your own deserializer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!