以编程方式在c#中添加[XmlIgnore]属性以进行序列化

use*_*672 2 c# xml xml-serialization

有谁知道如何以编程方式将[XmlIgnore]属性添加到c#中的类属性?

我想这样做只有一个类,有一个或两个字段被序列化,因为我需要在运行时.

提前谢谢了.

Pas*_*ash 7

通过将XmlAttributeOverrides对象传递给XmlSerializer构造函数,可以动态地覆盖XML序列化属性.

XmlAttributes samplePropertyAttributes = new XmlAttributes();
samplePropertyAttributes.XmlIgnore = true;

XmlAttributeOverrides sampleClassAttributes = new XmlAttributeOverrides();
sampleClassAttributes.Add(typeof(SampleClass), "SampleProperty", samplePropertyAttributes);

var serializer = new XmlSerialized(typeof(SampleClass), sampleClassAttributes);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅MSDN中的XmlAttributeOverrides类.

  • 另请注意,XmlSerializer(Type, XmlAttributeOverrides) 构造函数会在运行时动态创建程序集,并且不会缓存它!因此,每次调用此构造函数都会创建另一个程序集,这可能会导致内存泄漏。XmlSerializer 是线程安全的,因此如果您要使用此构造函数,最好缓存您创建的 XmlSerializer (2认同)