gpt4 book ai didi

C# - XmlIgnore 不适用于 override 或 new 修饰符

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:27 24 4
gpt4 key购买 nike

[TestFixture]
public class XmlIgnoreWithNewModifierTest
{
public class Parent
{
public int Name { get; set; }
}

public class Child : Parent
{
[XmlIgnore]
public new int Name
{
get { throw new NotImplementedException(); }
}
}

[Test]
public void Test()
{
var serializer = new XmlSerializer(typeof(Child));
var stream = new MemoryStream();

// Throws
serializer.Serialize(stream, new Child());
}
}

最后一行代码将抛出 InvalidOperationException 并带有内部 NotImplementedException。使 Parent.Name 虚拟和 Child.Name 覆盖没有帮助。

我想知道是否可以让 XmlIgnore 只对 Child.Name 起作用而不对 Parent.Name 起作用?

最佳答案

如本回答所述: Excluding some properties during serialization without changing the original class

你应该使用:

XmlAttributes attributes = new XmlAttributes { XmlIgnore = true };
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Parent), "Name", attributes);

XmlSerializer serialize = new XmlSerializer(typeof(Child), overrides);

关于C# - XmlIgnore 不适用于 override 或 new 修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593735/

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