获取 Char 枚举的更好方法
有没有一种更简洁的方法来获取 C# 中枚举的 char 值。
public enum DivisionStatus
{
None = 'N',
Active = 'A',
Inactive = 'I',
Waitlist = 'W'
}
string status = Enums.DivisionStatus.Active.ToString()[0].ToString(); // "A"
Is there a cleaner way to get the char value of an enum in C#.
public enum DivisionStatus
{
None = 'N',
Active = 'A',
Inactive = 'I',
Waitlist = 'W'
}
string status = Enums.DivisionStatus.Active.ToString()[0].ToString(); // "A"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
var status = (char)Enums.DivisionStatus.Active;
应该完全符合您的要求。如果枚举文本的第一个字符与底层 char 值不匹配,那么您之前执行此操作的方式将不起作用。这也适用于以 int 作为支持类型的枚举。
var status = (char)Enums.DivisionStatus.Active;
should do exactly what you want. The way you were doing it before wouldn't have worked if the first character of the enum text didn't match the underlying char value.This also works for enums that have an int as a backing type.
我构建了一个解决问题的“伪枚举”。在您的情况下,它可能看起来像:
您可以像枚举一样使用它,在 ToString() 上返回 char 枚举值而不进行强制转换:
I build a "pseudo-enum" that solves the problem. In your case it could look like:
You can use it like an enum that returns the char enum value on ToString() without casting:
简单的铸造工作,我尝试过:
Simple casting works, I tried it:
我只会转换枚举值而不调用 ToString:
或者也许你需要这样做
I would just cast the enum value without calling ToString:
Or maybe you'd need to do
只需转换值:
请注意,这将使用值而不是标识符。
Enums.DivisionStatus.Active
值是'A'
的字符代码,因为这是您定义的值。直接使用该值比查找该值的标识符更快。
Just cast the value:
Note that this will use the value instead of the identifier. The
Enums.DivisionStatus.Active
value is the character code of'A'
, as that is the value that you have defined.Using the value directly is faster than looking up the identifier for the value.
您还可以使用静态类。不过,如果您始终将值用作字符串,则可以轻松地将每个属性设置为字符串。此方法的优点之一是您可以为将在 IntelliSense 中显示的每个项目添加描述。
You could also use a static class. Although, if you're always going to use the values as strings, you could just as easily make each property a string instead. One advantage of this method is that you can add descriptions for each item that will show up in the IntelliSense.