枚举的序列化失败
我为此使用 .NET 3.5。
我有一个枚举:
[System.SerializableAttribute()]
public enum MyEnum
{
[System.Xml.Serialization.XmlEnumAttribute("035")]
Item1,
Item2
}
我在类中使用这个枚举:
[System.SerializableAttribute()]
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public MyEnum MyEnum { get; set; }
}
现在我想创建一个新的 Eplomyee 实例,通过从字符串转换它来设置 MyEnum 属性。 然后将其序列化并保存在文件中。
Employee bob = new Employee() {Id = 1, Name = "Bob"};
bob.MyEnum = (MijnEnum)Enum.Parse(typeof(MyEnum), string.Format(CultureInfo.InvariantCulture, "{0}", "035"));
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
FileInfo fi = new FileInfo(@"C:\myfile.xml");
using (FileStream stream = fi.OpenWrite())
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, OmitXmlDeclaration = true, Indent = true };
using (XmlWriter writer = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(writer, bob); // this is place where it goes wrong
}
}
如果我对此进行调试,我会看到 bob.MyEnum
的值是 35
当我尝试序列化时,出现异常:
生成 XML 文档时出错。
实例验证错误:“35”不是有效值 WindowsFormsApplication.MyEnum。
出了什么问题,我该如何解决这个问题?
I use .NET 3.5 for this.
I have an enum:
[System.SerializableAttribute()]
public enum MyEnum
{
[System.Xml.Serialization.XmlEnumAttribute("035")]
Item1,
Item2
}
I use this enum in a class:
[System.SerializableAttribute()]
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public MyEnum MyEnum { get; set; }
}
Now I want to create a new Eplomyee-instance, set the MyEnum-property by casting it from a string.
Then serialize it and save it in a file.
Employee bob = new Employee() {Id = 1, Name = "Bob"};
bob.MyEnum = (MijnEnum)Enum.Parse(typeof(MyEnum), string.Format(CultureInfo.InvariantCulture, "{0}", "035"));
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
FileInfo fi = new FileInfo(@"C:\myfile.xml");
using (FileStream stream = fi.OpenWrite())
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, OmitXmlDeclaration = true, Indent = true };
using (XmlWriter writer = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(writer, bob); // this is place where it goes wrong
}
}
If I debug this, I see that the value of bob.MyEnum
is 35
When I try to serialize, I get an exception:
There was an error generating the XML document.
Instance validation error: '35' is not a valid value for
WindowsFormsApplication.MyEnum.
What is going wrong and how can I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让我们开始吧:
现在,
XmlEnumAttribute
控制如何在 XML 中序列化和反序列化该值。它与您的其余代码无关!(抱歉,上限,但似乎没有其他人明白这一点)。
因此,当
MyEnum.Item1
的值被序列化时,将发出“035”。现在的问题是你想如何分配它。
这很简单。就像平常一样分配即可。这些属性不会改变正常代码的语义,一切都保持不变。
示例:
这里绝对没有理由考虑
Enum.Parse
。枚举类型和值是静态已知的。如果您确实想使用
Enum.Parse
,请像平常一样使用它,例如:Let's start:
Now the
XmlEnumAttribute
controls how that value is serialized and deserialized in XML.IT HAS NOTHING TO WITH THE REST OF YOUR CODE! (sorry for the caps, but no-one else seems to get this).
So when a value of
MyEnum.Item1
get serialized, "035" will be emitted.Now the problem is how you want to assign this.
It is simple. Just assign like you would normally do. None these attributes change semantics of normal code, everything stays the same.
Example:
There is abolutely no reason why
Enum.Parse
should even be considered here. The enum type and value is statically known.If you did want to use
Enum.Parse
, use it like normal, example:发生这种情况是因为
Enums
在内部存储为int
。因此,您的语句bob.MyEnum = (MijnEnum)Enum.Parse(typeof(MyEnum), string.Format(CultureInfo.InvariantCulture, "{0}", "035"));
运行没有问题。如果进行调试,bob.MyEnum
的值为35
。当您对其进行反序列化时,反序列化器会搜索与 int 值 35 匹配的enum
,但该值不存在,因为您指定了 Item1 和 Item2。因此你会得到一个错误。这会起作用
理想情况下你应该这样做
希望这对你有帮助。
This is happening because,
Enums
are internally store asint
. Hence your statementbob.MyEnum = (MijnEnum)Enum.Parse(typeof(MyEnum), string.Format(CultureInfo.InvariantCulture, "{0}", "035"));
is running without issue. If you debug, value ofbob.MyEnum
is35
. When you deserialize this, deserializer searches for matchingenum
with int value 35, which is not there, as you are specifying Item1 and Item2. Hence you get an error.This will work
Ideally you should be doing this
Hope this helps you.
我改变了枚举解析。
我使用反射将字符串解析为枚举,如本文所述: http://www.codeguru.com/csharp/csharp/cs_syntax/enumerations/article.php/c5869
现在它可以工作了。
I changed the enum-parsing.
I used reflection to parse the string to the enum, as described in this article: http://www.codeguru.com/csharp/csharp/cs_syntax/enumerations/article.php/c5869
And now it works.