是否可以隐藏继承的数据成员

本文关键字:数据成员 继承 隐藏 是否 | 更新日期: 2023-09-27 17:55:32

我有两个类。基类具有具有数据成员的公共属性。现在,我不希望在子类中序列化此属性。我无法控制父类,其他几个类确实继承了它。

有没有办法从 WCF 使用的 XmlSerializer 中"隐藏"此属性?(此处的上下文是 WCF RESTful Web 服务)。

是否可以隐藏继承的数据成员

是的,可以使用 XmlAttributeOverrides 类和 XmlIgnore 属性。下面是基于 MSDN 的示例:

public class GroupBase
{
    public string GroupName;
    public string Comment;
}
public class GroupDerived : GroupBase
{   
}
public class Test
{
   public static void Main()
   {
      Test t = new Test();
      t.SerializeObject("IgnoreXml.xml");
   }
   public XmlSerializer CreateOverrider()
   {
      XmlAttributeOverrides xOver = new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();
      attrs.XmlIgnore = true; //Ignore the property on serialization
      xOver.Add(typeof(GroupDerived), "Comment", attrs);
      XmlSerializer xSer = new XmlSerializer(typeof(GroupDerived), xOver);
      return xSer;
   }
   public void SerializeObject(string filename)
   {
      XmlSerializer xSer = CreateOverrider();
      GroupDerived myGroup = new GroupDerived();
      myGroup.GroupName = ".NET";
      myGroup.Comment = "My Comment...";
      TextWriter writer = new StreamWriter(filename);
      xSer.Serialize(writer, myGroup);
      writer.Close();
   }

结果:

<?xml version="1.0" encoding="utf-8"?>
<GroupDerived xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GroupName>.NET</GroupName>
</GroupDerived>

结果与XmlIgnore = false;

<?xml version="1.0" encoding="utf-8"?>
<GroupDerived xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GroupName>.NET</GroupName>
  <Comment>My Comment...</Comment>
</GroupDerived>