gpt4 book ai didi

.net - 使用 XmlSerializer 时如何忽略派生类中基类的属性?

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

我有一个这样的类(class):

[Serializable]
public class Structure
{
#region Constants and Fields

/// <summary>
/// The description.
/// </summary>
private string description;


#endregion


/// <summary>
/// Gets or sets the Description of the subclass i.e subtype of structure
/// </summary>
public string Description
{
get
{
return this.description;
}

set
{
this.description = value;
}
}
}

下面的另一个类继承了上面的类:
[XmlRoot(Namespace = "TestNamespace", ElementName = "OrgStructure")]
public class OrgStructure : Structure
{


private long orgDeptID;

/// <summary>
/// The description
/// </summary>
private string description;

public long OrgDeptID
{
get
{
return this.orgDeptID;
}

set
{
this.orgDeptID= value;

}
}
}

我正在将 ASMX 服务迁移到 WCF,使它们与现有的 ASMX 客户端兼容。所以我必须使用 XmlSerializer而不是 DataContractSerializer .
OrgStructure声明为 MessageBodyMemberOperationContract 的响应类型中.

ASMX 客户端 期待 Description在 XML 消息中。所以我试图隐藏(使用 new 运算符) Description派生类中的属性并应用 XmlIgnoreAttribute到它。但它仍然序列化了这个属性。

(请注意 description 变量的声明。我不知道为什么开发人员再次声明派生类而不是将它 protected 保留在基类本身中。)

使用 XmlSerializer 时如何忽略派生类中基类的属性?我不能在基类中忽略它,因为 Structure 的其他子类型需要它。

最佳答案

在基类中添加:

public virtual bool ShouldSerializeDescription() { return true; }

并在派生类中添加:
public override bool ShouldSerializeDescription() { return false; }

这是 XmlSerializer的模式承认,但必须在与成员( Description )相同的级别上声明,因此需要使其成为 virtual .

如果它冒犯了眼睛,请添加一些:
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]

到它 - 但它必须是 public上类。

关于.net - 使用 XmlSerializer 时如何忽略派生类中基类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6663969/

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