C#中的整数反序列化枚举整数、序列化

2023-09-03 06:33:18 作者:学渣代言人

是否有可能从C#一个int反序列化的枚举。例如如果我有下面的类:

Is it possible to deserialize an enum from an int in c#. e.g. If I have the following class:

class Employee
{
   public string Name { get; set;}
   public int EmployeeTypeID { get; set;}
}

我可以轻松地从XML创建此

I can easily create this from XML

   <Employee>
       <Name>Joe Bloggs</Name>
       <EmployeeTypeID>1</EmployeeTypeID>
   </Employee>

使用这样的事情:

using something like this:

Employee employee = (Employee)new XmlSerializer(typeof(Employee)).Deserialize(XmlReader);

通过参与很少的工作,这让我使用,我可以养活一个选择命令,连接字符串和类型用于所有数据库对象和检索对象的数组,而无需任何进一步的映射一个通用的服务。不过,我已经完蛋与枚举。现在假设,而不是作为一个整数EmployeeType是一个枚举:

With very little work involved, this allows me to use one generic service that I can use for all database objects by feeding a select command, connection string and a type in to and retrieve an array of objects without any need for further mapping. However I have come unstuck with enums. Supposing now instead of being an integer EmployeeType is an enum:

public enum EmployeeTypeEnum
{
   Admin = 1,
   Sales = 2
}

所以我的班变成了:

so my class becomes:

class Employee
{
   public string Name { get; set;}
   public EmployeeTypeEnum EmployeeTypeID { get; set;}
}

我可以使用相同的XML和使C#认识到EmployeeTypeID在XML的int值应与枚举的int值对应?类似的还有其他的问题在那里,但没有有一个非常满意的答案是很旧,而且涉及大规模改变code。我希望有一个更好的解决办法...

Can I use the same XML and make c# recognise that the int value of EmployeeTypeID in the xml should correspond with the int value of the enum? There are other questions similar out there, but none have a very satisfactory answer are quite old, and involve wholesale changes to code. I am hoping for a better solution...

作为一个可能的单独的说明(略预期一些回应的),用枚举这个做法最好避免?我应该使用键 - 值对?我将总是使用键 - 值对(或类似)是否有可能是变化的,但在这种情况下EmployeeType是固定的,永远不会改变。

As a possible separate note (and slightly in anticipation of some responses), is using enums for this a practise best avoided? Should I be using Key-Value pairs? I would always use Key-value pairs (or similar) if there were likely to be changes, but in this case EmployeeType is fixed and will never change.

推荐答案

理论上的(=我还没有尝试过),添加 XmlEnum将属性,以你的枚举值应该做的伎俩:

Theoretically (= I haven't tried it), adding the XmlEnum attribute to your enum values should do the trick:

public enum EmployeeTypeEnum 
{ 
    [XmlEnum("1")] Admin = 1, 
    [XmlEnum("2")] Sales = 2 
} 

这告诉XmlSerializer的是EmployeeTypeEnum.Admin的价值是被序列化为字符串 1 的(反之亦然)的(这是你需要)。

This tells XmlSerializer that a value of EmployeeTypeEnum.Admin is to be serialized as the string 1 and vice-versa (which is what you need).

关于你的边注:我没有看到这里使用枚举是一个问题。如果在数据库中的值是整数,并且有固定含义,枚举是一个很好的解决方案,此外,作为一个文件,以数据库值。

Regarding your side note: I don't see using enums here as a problem. If the values in the database are integers and have a fixed meaning, enums are a good solution and, in addition, serve as a documentation to the database values.