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

时间:2014-03-31 11:38:37

标签: c# wcf serialization

我有两节课。基类有一个带有DataMember的公共属性。现在,我不希望在子类中序列化此属性。我无法控制父类,其他几个类也继承它。

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

1 个答案:

答案 0 :(得分:3)

是的,可以使用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>