[英]Serialize Flags enum with two equal values
I want to define a flag enum like the following: 我想定义一个如下所示的标志枚举:
[Flags]
[Serializable]
public enum Numbers
{
[XmlEnum(Name = "One")]
One = 0x1,
[XmlEnum(Name = "Two")]
Two = 0x2,
[XmlEnum(Name = "Three")]
Three = 0x4,
[XmlEnum(Name = "OddNumbers")]
OddNumbers = One | Three,
[XmlEnum(Name = "EvenNumbers")]
EvenNumbers = Two,
[XmlEnum(Name = "AllNumbers")]
AllNumbers = One | Two | Three
}
Suppose I create an object which has a Numbers
property and I set that property to EvenNumbers
. 假设我创建了一个具有
Numbers
属性的对象,并将该属性设置为EvenNumbers
。 Today, only Two
is included in property, but I want to specify EvenNumbers
so that if I add Four
in the future it will be included in the property as well. 今天,属性中只包含
Two
,但是我想指定EvenNumbers
这样如果我将来添加Four
,它也将包含在属性中。
However, if I serialize this object using XmlSerializer.Serialize
, the XML will say Two
because today this is the same underlying value. 但是,如果我使用
XmlSerializer.Serialize
序列化此对象,XML将说Two
因为今天这是相同的基础值。
How can I force the serializer to serialize this property as EvenNumbers
? 如何强制序列化程序将此属性序列化为
EvenNumbers
?
Do something like that: Mark the Number
property as XmlIgnore
and create another property type of string
for return the string value of enum. 做类似的事情:将
Number
属性标记为XmlIgnore
并创建另一个属性类型的string
以返回enum的字符串值。
[Serializable]
public class NumberManager
{
[XmlIgnore]
public Numbers Numbers { get; set; }
[XmlAttribute(AttributeName="Numbers")]
public string NumbersString
{
get { return Numbers.ToString(); }
set { Numbers = (Numbers) Enum.Parse(typeof (Numbers), value); }
}
}
Then serialize the NumberManager
. 然后序列化
NumberManager
。
I hope it helps. 我希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.