Dav*_*use 59 c# enums return-type return-value
我有以下枚举:
public enum Urgency {
VeryHigh = 1,
High = 2,
Routine = 4
}
Run Code Online (Sandbox Code Playgroud)
我可以像这样获取一个枚举"值"字符串:
((int)Urgency.Routine).ToString() // returns "4"
Run Code Online (Sandbox Code Playgroud)
注意:这与以下内容不同:
Urgency.Routine.ToString() // returns "Routine"
(int)Urgency.Routine // returns 4
Run Code Online (Sandbox Code Playgroud)
有没有办法可以创建一个扩展类,或者一个静态的utliity类,它会提供一些语法糖?:)
小智 109
您应该只能使用Enums ToString方法的重载为其提供格式字符串,这将打印出枚举值作为字符串.
public static class Program
{
static void Main(string[] args)
{
var val = Urgency.High;
Console.WriteLine(val.ToString("D"));
}
}
public enum Urgency
{
VeryHigh = 1,
High = 2,
Low = 4
}
Run Code Online (Sandbox Code Playgroud)
Stu*_*wig 23
为了实现枚举的更多"人类可读"描述(例如"非常高"而不是"示例中的"非常高"),我使用属性修饰了枚举值,如下所示:
public enum MeasurementType
{
Each,
[DisplayText("Lineal Metres")]
LinealMetre,
[DisplayText("Square Metres")]
SquareMetre,
[DisplayText("Cubic Metres")]
CubicMetre,
[DisplayText("Per 1000")]
Per1000,
Other
}
public class DisplayText : Attribute
{
public DisplayText(string Text)
{
this.text = Text;
}
private string text;
public string Text
{
get { return text; }
set { text = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
然后,使用这样的扩展方法:
public static string ToDescription(this Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(
typeof(DisplayText),
false);
if (attrs != null && attrs.Length > 0)
return ((DisplayText)attrs[0]).Text;
}
return en.ToString();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以打电话
myEnum.ToDescription()为了将您的枚举显示为更易读的文本.
如果您只想处理这个枚举,请使用 Mark Byer 的解决方案。
对于更通用的解决方案:
public static string NumberString(this Enum enVal)
{
return Convert.ToDecimal(enVal).ToString("0");
}
Run Code Online (Sandbox Code Playgroud)
转换为十进制意味着您不需要显式处理 8 种不同的允许基础整数类型,因为它们都无损地转换为十进制而不是相互转换(ulong 和 long 不会在彼此之间无损转换,但两者都可以处理其他的)。这样做可能会更快(特别是如果你在比较顺序中选择得很好),但是为了相对较少的收益而更加冗长。
编辑:
以上虽然不如弗兰肯托什,弗兰肯托什把问题看透了真正的问题,并且非常雄辩地解决了它。