gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:12:34 24 4
gpt4 key购买 nike

我有两个类(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com