WCF Datacontract - 它是否支持可空数据成员?

时间:2010-03-11 16:47:13

标签: wcf

    [DataMember]
    public int? NumberOfPages;   //////////// Is this supported????
    [DataMember]
    public bool? Color;          //////////// Is this supported????
    [DataMember]
    public int? BulkQuantity;
    [DataMember]

5 个答案:

答案 0 :(得分:32)

是的,当然!

创建可以为空的数据成员应该没有任何问题,它们将在生成的WSDL / XSD中作为“xs:nillable = true”成员处理。没问题。

答案 1 :(得分:7)

是的,请参阅Types Supported by the Data Contract Serializer

  

数据协定序列化程序完全支持可空类型。

答案 2 :(得分:4)

@Kahoon和Batwad:

我们通过两个步骤使用nullable<>?类型解决了这个问题:

  1. 在包含通用字段的类中,按如下方式定义字段:

    nullable<GenType> MyField {get; set;}
    
  2. 在使用此基类的数据协定中,您可以使用某些类似注释的标记定义序列化程序/反序列化程序已知的元素。在这里,我们定义了例如:

    [Serializable]
    [DataContract]
    [KnownType(typeof(BaseClass<nullable<DateTime>>))]
    

    我认为,您可以使用BaseClass<nullable<DateTime>>代替BaseClass<DateTime?>

  3. 在此之后,通用空值的序列化对我们有用。

答案 3 :(得分:1)

通常它可以工作,但如果拥有可空成员的类是通用的,则可能会遇到问题。有人也遇到了和我一样的问题:https://web.archive.org/web/20160617092729/http://discoveringdotnet.alexeyev.org/2009/06/wcf-nullable-values-are-not-working-in.html

答案 4 :(得分:0)

在我的情况下看起来传入的Nullable Integer被视为空字符串而非空值

所以这就是我如何处理代码中的可空

    [XmlIgnore]
    public int? NumberOfPagesCount{ get; set; }

    [XmlElement("NumberOfPages")]
    public string NumberOfPagesText
    {
        get { return this.NumberOfPagesCount.HasValue ? this.NumberOfPagesCount.Value.ToString("F2") : string.Empty; }
        set
        {
            if (!string.IsNullOrEmpty(value))
            {
                this.NumberOfPagesCount= Convert.ToInt32(value);
            }
            else
            {
                this.NumberOfPagesCount= null;
            }
        }
    }
相关问题