枚举元素上的自定义名称 [英] Custom names on enum elements

查看:158
本文介绍了枚举元素上的自定义名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [Flags] 
public enum Crazies
{
One = 2,
Two = 3,
Three = 4
}

现在,当我强制不同的值被拼接时,我会得到美丽的舌头中的文字,与数字的通常含义有很大的不同。假设现在用户喜欢自然数的更传统的定义,并且希望看到文本 Two ,尽管变量值是一个(注意它是 Crazies.One )。



最简单的方法是映射元素的预定义名称的字符串?现在我会去跟以下的东西一样,但我不太喜欢它。

  private static String DecrazyfyCrazies(Crazies 
{
开关(错误)
{
case Crazies.One:returnTwo;
case Crazies.Two:returnThree;
}
返回四;
}


解决方案

如果您需要 int 只是转换为int

  return(int)Crazies.One; 

有关更多自定义字符串显示,您可以使用显示名称



ie

  public enum Crazies 
{
[Display(Name =Custom Name for一个)]
一个= 2,
[显示(名称=两个自定义名称)]
二= 3
}

详细了解加强你的枚举


Suppose there's an enum like so.

[Flags]
public enum Crazies
{
  One = 2,
  Two = 3,
  Three = 4
}

Now, when I force the different values to be stringified, I get the text in the beautiful tongue, which differ considerably from the usual meaning of the numerics. Suppose now that the users prefer a more conventional definition of the natural numbers and wish to see the text "Two", although the variable value is One (NB it's Crazies.One).

What'd be the simplest way to map the stringification of the predefined names of the elements? Right now I'll go with something like the following but I don't really like it.

private static String DecrazyfyCrazies(Crazies wrong)
{
  switch(wrong)
  {
    case Crazies.One: return "Two";
    case Crazies.Two: return "Three";
  }
  return "Four";
}

解决方案

If you need int just cast to int

return (int)Crazies.One;

For more custom string display you can use display name

i.e

public enum Crazies
{
  [Display(Name="Custom Name for One")]
  One = 2,
  [Display(Name="Custom Name for Two")]
  Two = 3     
}

See more about Power Up Your Enum

这篇关于枚举元素上的自定义名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆