0

我将以下实体基类标记为可序列化:

[Serializable]
public abstract class EntityBase
{
    public bool Is_ActiveNull = true;
    [XmlElement(ElementName = "Is_ActiveFromNull")]
    ...  

然后我有从基本实体继承的具体实体:

[Serializable]
public class ContactEntity : EntityBase
{
 ...

我有一个 WCF 服务,它使用这个实体作为合同中的输入参数。

当我从客户端创建服务引用时,它会创建一个 reference.cs,它忽略字段 Is_ActiveNull 的默认值。

这是 reference.cs 文件中的 EntityBase 类:

public partial class EntityBase : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged 
{
    private bool Is_ActiveNullField;

    [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
    public bool Is_ActiveNull {
        get {
            return this.Is_ActiveNullField;
        }
        set {
            if ((this.Is_ActiveNullField.Equals(value) != true)) {
                this.Is_ActiveNullField = value;
                this.RaisePropertyChanged("Is_ActiveNull");
            }
        }
    }
    ...

在这种情况下,Is_ActiveNullField 默认设置为 false。

我的问题是如何保留默认值?

谢谢

4

1 回答 1

0

Their is no such attribute that will preserve the default value for public bool Is_ActiveNull

But you can achieve it when Deseralizing happens like this

You will have to add EmitDefaultValue on you field

 [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, EmitDefaultValue=false)]
    public bool Is_ActiveNull {

and then 

[OnDeserializing]
    void BeforeDeserialization(StreamingContext ctx)
    {
        this.Is_ActiveNull = false;
    }

Mind you the MSDN also gives a Not on practice for EmitDefaultValue

Setting the EmitDefaultValue property to false is not a recommended practice. It should only be done if there is a specific need to do so (such as for interoperability or to reduce data size).

于 2012-07-11T08:00:56.797 回答