简体   繁体   English

如何从 char 值中检索 Enum?

[英]How can I retrieve Enum from char value?

I have the following enum我有以下枚举

public enum MaritalStatus
{
    Married = 'M',
    Widow = 'W',
    Widower = 'R',
    Single='S'
}

In one function I have for exp: 'S' , and I need to have MaritalStatus.Single .在一个函数中,我有 exp: 'S' ,我需要MaritalStatus.Single

How can I get the enum from the character value ?如何从字符值中获取枚举 For string I found this solution, but it gets exception for Char.对于字符串,我找到了这个解决方案,但它对 Char 有例外。

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

The enum values, though defined with char s actually equal to the int representation of that char.枚举值虽然用char定义,但实际上等于该 char 的int表示。 It is as if you defined it as following:就好像您将其定义如下:

public enum MaritalStatus
{
    Married = 77,
    Widow = 87,
    Widower = 82,
    Single=83
} 

Convert char to int and then assign to the enum:char转换为int ,然后分配给枚举:

int m = 'M'; // char of `M` equals to 77
MaritalStatus status = (MaritalStatus)m;  

Console.WriteLine(status == MaritalStatus.Married); // True
Console.WriteLine(status == MaritalStatus.Single); // False

After playing with it a bit and putting it into a one liner I see that even the conversion to an int is not needed .在玩了一会儿并将其放入单行之后,我发现甚至不需要转换为int All you need is to cast as the enum:您所需要的只是将其转换为枚举:

MaritalStatus status = (MaritalStatus)'M'; // MaritalStatus.Married

I guess found One solution for that:我想为此找到了一个解决方案:

   (MaritalStatus)Enum.ToObject(typeof(MaritalStatus), 'S')

It gets me MaritalStatus.Single它让我MaritalStatus.Single

Enum.ToObject(enumType, byte) is the signature. Enum.ToObject(enumType, byte) 是签名。

There are multiple ways to get the enum Name from value.有多种方法可以从值中获取枚举名称。

string name =   ((MaritalStatus)'S').ToString();
string enumName =  Enum.GetName(typeof(MaritalStatus), 'S');

In C# 6.0 you can use nameof在 C# 6.0 中,您可以使用nameof

I was able to read the enum value of the character by changing the charValue to string and then reading the first character and casting it to my ENUM type.通过将 charValue 更改为字符串,然后读取第一个字符并将其转换为我的 ENUM 类型,我能够读取字符的枚举值。

Looks like this in code :在代码中看起来像这样:

( Marital Status ) ( charValue.ToString ( ) [ 0 ] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM