【问题标题】:How can I have a nullable enum serialized to an attribute [duplicate]如何将可空枚举序列化为属性[重复]
【发布时间】:2016-12-31 23:13:42
【问题描述】:

我有一个需要从 xml 反序列化的类,它有一个枚举属性,它作为属性存储在 xml 中。有时,此属性可能会丢失或具有“”作为值。 如何让序列化程序处理使 BorrowerResidencyType 属性可以为空?

XML:

<_RESIDENCE _StreetAddress="" _City="San Jose" _State="CA" BorrowerResidencyType="" />
<_RESIDENCE _StreetAddress="" _City="San Jose" _State="CA"  />

C#:

[System.CodeDom.Compiler.GeneratedCodeAttribute ( "System.Xml", "4.0.30319.17929" )]
[System.SerializableAttribute ()]
[System.Xml.Serialization.XmlTypeAttribute ( AnonymousType = true )]
public enum _RESIDENCEBorrowerResidencyType
{

    /// <remarks/>
    Current,

    /// <remarks/>
    Prior,
}

public class Test{
public string StreetAddress{get;set;}
public string City{get;set;}
[System.Xml.Serialization.XmlAttributeAttribute ()]
public _RESIDENCEBorrowerResidencyType BorrowerResidencyType{get;set;}
}

是否有其他库可以更智能地处理这种情况?

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    可能是这样的:

    public enum _RESIDENCEBorrowerResidencyType
    {
        [XmlEnum(Name="")]
        Default = 0,
    
        Current,
        Prior
    }
    

    【讨论】:

    • 此解决方案将使用值空字符串进行序列化。
    • @OlegPolezky:您可以通过在属性上设置 DefaultValue 属性来解决此问题,例如[DefaultValue(MyEnumType.Default)]
    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2019-03-15
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多