3
我有兩個班。基類具有帶DataMember的公共屬性。現在,我不希望此屬性在子類中被序列化。我無法控制父類,還有其他幾個類繼承自它。是否可以隱藏繼承的數據成員?
有沒有辦法從WCF使用的XmlSerializer中「隱藏」這個屬性? (這裏的上下文是一個WCF RESTful Web服務)。
我有兩個班。基類具有帶DataMember的公共屬性。現在,我不希望此屬性在子類中被序列化。我無法控制父類,還有其他幾個類繼承自它。是否可以隱藏繼承的數據成員?
有沒有辦法從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>