我有两个类(class)。基类有一个带有 DataMember 的公共(public)属性。现在,我不想在子类中序列化此属性。我无法控制父类,其他几个类确实继承自它。
有没有办法从 WCF 使用的 XmlSerializer 中“隐藏”这个属性? (此处的上下文是 WCF RESTful Web 服务)。
最佳答案
是的,可以使用 XmlAttributeOverrides
类,以及 XmlIgnore
属性(property)。这是基于 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>
关于c# - 是否可以隐藏继承的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22760605/