gpt4 book ai didi

c# - 了解 System.Xml.Serialization.XmlIgnoreAttribute 与基类

转载 作者:行者123 更新时间:2023-12-04 06:48:56 25 4
gpt4 key购买 nike

我有两个类,如下所示:

[Serializable]
[XmlInclude(typeof(SomeDerived))]
public class SomeBase
{
public string SomeProperty { get; set; }
}

public class SomeDerived : SomeBase
{
[XmlIgnore]
public new string SomeProperty { get; set; }
}

当我序列化 SomeDerived 的实例时我不希望看到 SomeProperty 的值.不过,我愿意。我尝试过其他方法,例如使用 SomeProperty声明为 virtualSomeBase并在 SomeDerived 中覆盖它.我仍然在 SomeDerived 的序列化实例中看到它.

谁能解释一下 XmlIgnoreAttribute 是怎么回事? ?

为了完整起见,我的反序列化代码如下
class Program
{
static void Main(string[] args)
{
SomeDerived someDerived = new SomeDerived { SomeProperty = "foo" };

XmlSerializer ser = new XmlSerializer(typeof(SomeBase));

MemoryStream memStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Default);
ser.Serialize(memStream, someDerived);

xmlWriter.Close();
memStream.Close();
string xml = Encoding.Default.GetString(memStream.GetBuffer());

Console.WriteLine(xml);
Console.ReadLine();
}
}

编辑

如果我将序列化程序声明更改为 new XmlSerializer(typeof(SomeDerived)),我会得到相同的行为.

最佳答案

试试这个。它使用 XmlSerializer 构造函数上的覆盖来传递一些序列化覆盖:

SomeDerived someDerived = new SomeDerived { SomeProperty = "foo" };

// Create the XmlAttributeOverrides and XmlAttributes objects.
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();

/* Use the XmlIgnore to instruct the XmlSerializer to ignore
the GroupName instead. */
attrs = new XmlAttributes();
attrs.XmlIgnore = true;
overrides.Add(typeof(SomeBase), "SomeProperty", attrs);

XmlSerializer ser = new XmlSerializer(typeof(SomeBase), overrides);

MemoryStream memStream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Default);
ser.Serialize(memStream, someDerived);

xmlWriter.Close();
memStream.Close();
string xml = Encoding.Default.GetString(memStream.GetBuffer());

关于c# - 了解 System.Xml.Serialization.XmlIgnoreAttribute 与基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3397331/

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