序列化可为空INT [英] Serialize a nullable int

查看:291
本文介绍了序列化可为空INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类具有可空中断?数据类型设置为序列化为XML元素。有什么办法来进行设置,所以如果该值是空的XML serialializer不会序列化的元素?

I have a class with a nullable int? datatype set to serialize as an xml element. Is there any way to set it up so the xml serialializer will not serialize the element if the value is null?

我试图添加[System.Xml.Serialization.XmlElement(ISNULLABLE = FALSE)]属性,但我得到一个运行时的序列化异常说出现了一个错误反映类型,因为ISNULLABLE不得设置为假的可空类型。考虑使用System.Int32的类型或删除从的XmlElement属性IsNullable属性。

I've tried to add the [System.Xml.Serialization.XmlElement(IsNullable=false)] attribute, but I get a runtime serialization exception saying there was a an error reflecting the type, because "IsNullable may not be set to 'false' for a Nullable type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute."

[Serializable]
[System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")]
public class Score
{
    private int? iID_m;
    ...

    /// <summary>
    /// 
    /// </summary>        
    public int? ID 
    { 
        get 
        { 
            return iID_m; 
        } 
        set 
        { 
            iID_m = value; 
        } 
    }
     ...
}

以上级将serailize到:

The above class will serailize to:

<Score xmlns="http://mycomp.com/test/score/v1">
    <ID xsi:nil="true" />
</Score>

但对于标识是空我不想ID元素可言,主要是因为当我在MSSQL使用OPENXML,它返回一个0,而不是空的,看起来像

But for IDs that are null I don't want the ID element at all, primarily because when I use OPENXML in MSSQL, it returns a 0 instead of null for an element that looks like

推荐答案

XmlSerializer的支持 ShouldSerialize {富}()模式,这样你就可以添加一个方法:

XmlSerializer supports the ShouldSerialize{Foo}() pattern, so you can add a method:

public bool ShouldSerializeID() {return ID.HasValue;}

也有 {}美孚指定模式 - 不知道XmlSerializer的支持,一个

There is also the {Foo}Specified pattern - not sure if XmlSerializer supports that one.

这篇关于序列化可为空INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆