我有一堂这样的课:
[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
在 OperationContract
的响应类型中声明为 MessageBodyMember
。
ASMX 客户端不期望 XML 消息中的描述
。因此,我尝试隐藏(使用 new
运算符)派生类中的 Description
属性,并将 XmlIgnoreAttribute
应用于它。但它仍然序列化这个属性。
(请注意 description
变量的声明。我不知道为什么开发人员再次声明派生类,而不是将其保护
保留在基类本身中。)
在使用 XmlSerializer 时,如何忽略派生类中基类的属性?我不能在基类中忽略它,因为 Structure
的其他子类型需要它。
最佳答案
在基类中添加:
public virtual bool ShouldSerializeDescription() { return true; }
并在派生类中添加:
public override bool ShouldSerializeDescription() { return false; }
这是 XmlSerializer
识别的模式,但必须在与成员 (Description
) 相同的级别进行声明,因此需要将其设为虚拟
.
如果它冒犯了眼睛,请添加一些:
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
它 - 但它必须是公开
才能工作。
关于.net - 使用XmlSerializer时如何忽略派生类中基类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6663969/