如何从XML序列化程序集中排除类

问题描述 投票:2回答:1

我有一个C#项目,我必须激活XML序列化程序集生成(csproj中的GenerateSerializationAssemblies)。

该项目包含一个派生自System.ComponentModel.Composition.ExportAttribute的类。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class MyExportAttribute : ExportAttribute
{ ... }

编译器失败,错误地抱怨ExportAttribute.ContractName上缺少公共属性设置器:

Error 10 Cannot deserialize type 'System.ComponentModel.Composition.ExportAttribute' because it contains property 'ContractName' which has no public setter. 

实际上我不想序列化这个类,所以我想将它从序列化程序集中排除。我能这样做吗?或者,指定要包含哪些类?

我到目前为止所尝试/想到的:

  • 使用空的setter隐藏MyExportAttribute中的ContractName属性(非虚拟),在getter中调用基本实现 - >相同的错误,序列化程序仍然想要访问基类的属性
  • 将XmlIgnore应用于MyExportAttribute.ContractName也没有帮助
  • 将类移动到其他项目是一种选择,但我想尽可能避免这种情况
  • ContractName属性上的XmlIgnore将解决我的问题,但当然我无法将其添加到ExportAttribute。是否有类似的XML序列化控制属性可以应用于类,因此序列化程序会忽略它?
c# xml-serialization
1个回答
1
投票

为了解决这个错误,我在给出IXmlSerializable问题的类上实现了sgen。我通过抛出NotImplementedException实现了每个必需的成员:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class MyExportAttribute
    : ExportAttribute
    // Necessary to prevent sgen.exe from exploding since we are
    // a public type with a parameterless constructor.
    , System.Xml.Serialization.IXmlSerializable
{
    System.Xml.Schema.XmlSchema System.Xml.Serialization.IXmlSerializable.GetSchema() => throw new NotImplementedException("Not serializable");
    void System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader reader) => throw new NotImplementedException("Not serializable");
    void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) => throw new NotImplementedException("Not serializable");
}
© www.soinside.com 2019 - 2024. All rights reserved.