枚举值的字符串 [英] Enum value to string
问题描述
有谁知道如何获得枚举值的字符串
Does anyone know how to get enum values to string?
例如:
private static void PullReviews(string action, HttpContext context)
{
switch (action)
{
case ProductReviewType.Good.ToString():
PullGoodReviews(context);
break;
case ProductReviewType.Bad.ToString():
PullBadReviews(context);
break;
}
}
编辑:
当尝试使用的ToString();编译器会抱怨,因为case语句期待一个常数。我也知道,toString()方法是与在智能感知
When trying to use ToString(); the compiler complains because the case statement is expecting a constant. I also know that ToString() is is striked out with a line in intellisense
推荐答案
是的,你可以使用<$ C $行删除线出C>的ToString()来得到一个字符串值枚举,但你不能在switch语句中使用的ToString()
。 switch语句需要常量表达式和的ToString()不评估,直到运行时,所以编译器将抛出一个错误。
Yes, you can use .ToString()
to get a string value for an enum, however you can't use .ToString()
in a switch statement. Switch statements need constant expressions, and .ToString() does not evaluate until runtime, so the compiler will throw an error.
要得到你想要的行为,一点点在方式改变,你可以使用 enum.Parse()
到动作
字符串转换为一个枚举值,打开该枚举值来代替。随着.NET 4中您可以使用 Enum.TryParse()
并做错误检查和处理的前期,而不是在开关本体。
To get the behavior you want, with a little change in the approach, you can use enum.Parse()
to convert the action
string to an enum value, and switch on that enum value instead. As of .NET 4 you can use Enum.TryParse()
and do the error checking and handling upfront, rather than in the switch body.
如果是我的话,我会解析字符串为一个枚举值和开关上,而不是对字符串进行切换。
If it were me, I'd parse the string to an enum value and switch on that, rather than switching on the string.
private static void PullReviews(string action, HttpContext context)
{
ProductReviewType review;
//there is an optional boolean flag to specify ignore case
if(!Enum.TryParse(action,out review))
{
//throw bad enum parse
}
switch (review)
{
case ProductReviewType.Good:
PullGoodReviews(context);
break;
case ProductReviewType.Bad:
PullBadReviews(context);
break;
default:
//throw unhandled enum type
}
}
这篇关于枚举值的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!