你如何在 C# 中将 XMLSerialize 用于枚举类型的属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2306299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you use XMLSerialize for Enum typed properties in c#?
提问by Rhubarb
I have a simple enum:
我有一个简单的枚举:
enum simple
{
one,
two,
three
};
I also have a class that has a property of type simple
. I tried decorating it with the attribute: [XmlAttribute(DataType = "int")]
. However, it fails when I try to serialize it using an XmlWriter
.
我还有一个具有 type 属性的类simple
。我尝试用属性装饰它:[XmlAttribute(DataType = "int")]
。但是,当我尝试使用XmlWriter
.
What is the proper way to do this? Do I have to mark the enum itself as well as the property, and if so, with which data type?
这样做的正确方法是什么?我是否必须标记枚举本身以及属性,如果是,使用哪种数据类型?
回答by Darin Dimitrov
There shouldn't be any problems serializing enum properties:
序列化枚举属性应该没有任何问题:
public enum Simple { one, two, three }
public class Foo
{
public Simple Simple { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var writer = XmlWriter.Create(Console.OpenStandardOutput()))
{
var foo = new Foo
{
Simple = Simple.three
};
var serializer = new XmlSerializer(foo.GetType());
serializer.Serialize(writer, foo);
}
}
}
produces:
产生:
<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Simple>three</Simple>
</Foo>
回答by zebrabox
As per Darin Dimitrov's answer - only extra thing I'd point out is that if you want control over how your enum fields are serialized out then you can decorate each field with the XmlEnumattribute.
根据 Darin Dimitrov 的回答 - 我要指出的唯一额外的事情是,如果您想控制枚举字段的序列化方式,那么您可以使用XmlEnum属性装饰每个字段。
public enum Simple
{
[XmlEnum(Name="First")]
one,
[XmlEnum(Name="Second")]
two,
[XmlEnum(Name="Third")]
three,
}