序列化对象时忽略继承的类 [英] Ignore inherited class when serializing object

查看:102
本文介绍了序列化对象时忽略继承的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从一个类继承并序列化新类时,我将获得所有所有属性. 我该如何预防呢? 我无法控制我继承的类.因此,我无法向其属性(XmlIgnore)添加属性.

When I inherit from a class and serialize the new class I get all all properties. How can I prevent that? I have no control over the class that I inherit from. So I can't add attributes to it's properties (XmlIgnore).

示例

class A 
{
    public string PropertyA {get;set;}
}

class B:A
{
    public string PropertyB {get;set;}
}

当我序列化一个类型为B的对象时,我同时获得了PropertyA和PropertyB,而我只想要PropertyB

When I serialize a object with the type of B then I get both PropertyA and PropertyB and I only want PropertyB

我使用的XML序列化

Type t = serObj.GetType();
XmlSerializer xser = new XmlSerializer(t);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

xser.Serialize(sw, serObj);
string xml = sw.ToString();

推荐答案

如果BA继承,则它继承PropertyA,您对此无能为力.如果在序列化B的实例时不想序列化PropertyA,也许您不应该一开始就继承A ...

If B inherits from A, it inherits PropertyA, and there's nothing you can do about it. If you don't want to serialize PropertyA when serializing an instance of B, perhaps you shouldn't be inheriting A in the first place...

无论如何,除非您自己实现IXmlSerializable,否则我不认为XML序列化可以帮助您完成您想做的事情.

Anyway, I don't think XML serialization can help you with what you're trying to do, unless you implement IXmlSerializable yourself...

这篇关于序列化对象时忽略继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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