.NET XmlSerializer的,忽略基类的属性属性、NET、XmlSerializer

由网友(一片海是一粒盐发的脾气°)分享简介:可以说,我们已经从基类System.Windows.Controls的一个derivided类SerializableLabel。Lets say we have a derivided class "SerializableLabel" from the base class "System.Windows.Con...

可以说,我们已经从基类System.Windows.Controls的一个derivided类SerializableLabel。

Lets say we have a derivided class "SerializableLabel" from the base class "System.Windows.Controls.

[XmlRoot("SerializableLabel")]
public class SerializableLabel : Label
{
    public string foo = "bar";
}

我想序列化这个类,但是忽略所有的父类中的属性。理想情况下,XML将类似于:

I'd like to serialize this class but ignore ALL of the properties in the parent class. Ideally the xml would look something like:

<SerializableLable>
    <foo>bar</foo>
</SerializableLable>

这是如何最好地实现?

我第一次尝试使用了典型的XmlSerializer的方法:

My first attempt used the typical XmlSerializer approach:

XmlSerializer s = new XmlSerializer(typeof(SerializableLabel));
TextWriter w = new StreamWriter("test.xml");
s.Serialize(w, lbl);
w.Close();

但是,这引发了一个异常,因为串行试图序列基类属性,它是一个接口(ICommand的命令)。

But this raises an exception because the serializer attempts to serialize a base class property which is an interface (ICommand Command).

推荐答案

以上问题(包括一所指出的太平绅士)一个可能的根源在于,你的类层次结构试图违反的里氏替换原则。在简单来说,派生类尝试不以做基类已经这样做了。再换句话说,你想创建一个派生的标签是不可替代的基础标签。

One possible root of the above problems (including the one pointed out by JP) is that your class hierarchy tries to violate the Liskov Substitution Principle. In simpler terms, the derived class tries not to do what the base class already does. In still other words, you're trying to create a derived label that is not substitutable for the base label.

最有效的补救措施在这里可能涉及解耦的两件事情, SerializableLabel 是试图做,(一)用户界面相关的功能和(b)存储序列化的数据,并让他们在不同的班级。

The most effective remedy here may involve decoupling the two things that SerializableLabel is tries to do, (a) UI-related functions and (b) storing serializable data, and having them in different classes.

阅读全文

相关推荐

最新文章