.NET XmlSerializer的,忽略基类的属性 [英] .net XmlSerializer, ignore base class properties

查看:323
本文介绍了.NET XmlSerializer的,忽略基类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说,我们已经从基类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.

这篇关于.NET XmlSerializer的,忽略基类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆