我们如何使用序列化私有字段?

时间:2012-05-02 15:58:16

标签: c#

class Program
{
    static void Main(string[] args)
    {
        var ball = new Ball();
        ball.MyApple.Name = "ramro apple";

        XmlSerializer ser = new XmlSerializer(typeof(Ball));
        var sb = new StringBuilder();
        var writer = new StringWriter(sb);

        ser.Serialize(writer, ball);

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sb.ToString());

        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
        object meroBall = ser.Deserialize(reader);
        Ball myBall = (Ball)meroBall;
    }
}

public class Apple
{
    public string Name
    {
        get;
        set;
    }
}

public class Ball
{
    public Ball()
    {
        _apple = new Apple();
    }

    public Apple MyApple
    {
        get { return _apple; }
    }

    private Apple _apple;
}

这里我在Ball类中定义了私有字段Apple _apple。它为MyApple提供了null值。但是,如果我将Apple _apple设置为公共字段,则会将值设为“ramro apple”。有没有办法通过使用私有字段获得该值?我试试

1 个答案:

答案 0 :(得分:1)

这是因为XmlSerializer仅适用于同时具有公共get和set的成员......如果为MyApple提供公共setter,它将起作用:

public class Ball
{
    public Ball()
    {
        _apple = new Apple();
    }

    public Apple MyApple
    {
        get { return _apple; }
        set { _apple = value; }
    }

    private Apple _apple;
}

这当然也假设Ball和Apple这两个类都有一个不带参数的公共构造函数。