2
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 的空值。但是,如果我将 Apple _apple 设置为公共字段,它会将值设为“ramro apple”。有没有办法通过使用私有字段来获得该值?我试试

4

1 回答 1

1

这是因为 XmlSerializer 仅适用于同时具有公共获取和设置的成员...如果您为 MyApple 提供公共设置器,它将起作用:

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

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

    private Apple _apple;
}

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

于 2012-05-02T16:06:46.213 回答