枚举的序列化失败

发布于 2025-01-04 11:46:03 字数 1366 浏览 2 评论 0原文

我为此使用 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋心╮凉 2025-01-11 11:46:03

让我们开始吧:

[System.SerializableAttribute()] // useless, valuetype is implicitly so
public enum MyEnum
{
    [System.Xml.Serialization.XmlEnumAttribute("035")]
    Item1,
    Item2
}

现在,XmlEnumAttribute 控制如何在 XML 中序列化和反序列化该值。

它与您的其余代码无关!(抱歉,上限,但似乎没有其他人明白这一点)。

因此,当 MyEnum.Item1 的值被序列化时,将发出“035”。

现在的问题是你想如何分配它。

这很简单。就像平常一样分配即可。这些属性不会改变正常代码的语义,一切都保持不变。

示例:

Employee bob = new Employee() {Id = 1, Name = "Bob", MyEnum = MyEnum.Item1};

这里绝对没有理由考虑 Enum.Parse。枚举类型和值是静态已知的。

如果您确实想使用 Enum.Parse,请像平常一样使用它,例如:

Enum.Parse(typeof(MyEnum), "Item1")

Let's start:

[System.SerializableAttribute()] // useless, valuetype is implicitly so
public enum MyEnum
{
    [System.Xml.Serialization.XmlEnumAttribute("035")]
    Item1,
    Item2
}

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:

Employee bob = new Employee() {Id = 1, Name = "Bob", MyEnum = MyEnum.Item1};

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:

Enum.Parse(typeof(MyEnum), "Item1")
旧故 2025-01-11 11:46:03

发生这种情况是因为 Enums 在内部存储为 int。因此,您的语句 bob.MyEnum = (MijnEnum)Enum.Parse(typeof(MyEnum), string.Format(CultureInfo.InvariantCulture, "{0}", "035")); 运行没有问题。如果进行调试,bob.MyEnum 的值为 35。当您对其进行反序列化时,反序列化器会搜索与 int 值 35 匹配的 enum,但该值不存在,因为您指定了 Item1 和 Item2。因此你会得到一个错误。

这会起作用

 bob.MyEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "35");

 public enum MyEnum {
   Item1 = 35,
   Item2
 }

理想情况下你应该这样做

 bob.MyEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "Single");

 public enum MyEnum {
   [System.Xml.Serialization.XmlEnumAttribute("Single")]
   Item1,
   Item2
 }

希望这对你有帮助。

This is happening because, Enums are internally store as int. Hence your statement bob.MyEnum = (MijnEnum)Enum.Parse(typeof(MyEnum), string.Format(CultureInfo.InvariantCulture, "{0}", "035")); is running without issue. If you debug, value of bob.MyEnum is 35. When you deserialize this, deserializer searches for matching enum with int value 35, which is not there, as you are specifying Item1 and Item2. Hence you get an error.

This will work

 bob.MyEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "35");

 public enum MyEnum {
   Item1 = 35,
   Item2
 }

Ideally you should be doing this

 bob.MyEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "Single");

 public enum MyEnum {
   [System.Xml.Serialization.XmlEnumAttribute("Single")]
   Item1,
   Item2
 }

Hope this helps you.

一个人练习一个人 2025-01-11 11:46:03

我改变了枚举解析。

我使用反射将字符串解析为枚举,如本文所述: 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文