[英]how to make switch statement generic in c#
I want to use switch statement in c#. 我想在c#中使用switch语句。 but instead of using a constant in the case expression I want to use an enumeration value.
但是我不想在case表达式中使用常量,而是要使用枚举值。 How do I use this.
我该如何使用。 If i try to use it like:
如果我尝试像这样使用它:
string strPageMode=...//some value;
switch (strPageMode)
{
case ModesEnum.SystemHealth:
//some code
break;
}
giving error. 给出错误。 what have to use then ?
那要用什么呢? I don't want to use If statement.
我不想使用If语句。
If it is a string then this will work: 如果它是一个字符串,那么它将起作用:
ModesEnum res;
//Implicit generic as opposed to Enum.Parse which returns object
Enum.TryParse(strPageMode, out res); //returns false if parsing failed
switch (res)
{
case ModesEnum.SystemHealth:
break;
}
As noted, the generic TryParse
is not available in < .Net 4.0
. 如前所述,通用的
TryParse
在< .Net 4.0
不可用。 Otherwise, use the Enum.Parse
. 否则,请使用
Enum.Parse
。
How is strPageMode
declared? 如何声明
strPageMode
? It needs to be an instance of ModesEnum
, I'm guessing it is a string. 它必须是
ModesEnum
的实例,我猜它是一个字符串。
Assuming that strPageMode
represents the name of one possible value of ModesEnum, you could do this: 假设
strPageMode
表示strPageMode
的一个可能值的名称,则可以执行以下操作:
switch (Enum.Parse(typeof(ModesEnum), strPageMode, false))
{
... as before
}
An enumeration literal (rather than the current value of a variable of that enumeration type) is a constant. 枚举文字(而不是该枚举类型的变量的当前值) 是一个常量。
There is a specific sense of the word "generic" in .NET and a general sense in English. 在.NET中,“通用”一词有特定含义,而在英语中则具有一般意义。 I don't understand what this has to do with either.
我不明白这与这有什么关系。
Based on the quasi-Hungarian name I'm guessing that strPageMode is a string (please tell me you don't really name variables like that in C# code). 基于准匈牙利名称,我猜测strPageMode是一个字符串(请告诉我,您实际上并没有像C#代码中那样命名变量)。 Considering switch as a sort of syntactic sugar for a set of if-else statements, this means you are doing an equality comparison between a string and an enum.
将switch视为一组if-else语句的语法糖,这意味着您正在字符串和枚举之间进行相等比较。 If this were allowed it would be rather pointless, as the string being a string and the enum being an enum, they are inherently never going to be equal whatever their values are.
如果允许这样做,那将是毫无意义的,因为字符串是字符串,而枚举是枚举,无论它们的值是什么,它们本质上永远不会相等。
You need to either parse the string into a ModesEnum value, and use that in the switch statement, or else make the case values strings with ModesEnum.SystemHealth.ToString(). 您需要将字符串解析为ModesEnum值,并在switch语句中使用它,或者使用ModesEnum.SystemHealth.ToString()将大小写值字符串设置为字符串。
In one of my projects, I have used switch case in the similar manner. 在我的一个项目中,我以类似的方式使用了开关盒。
switch(UserType)
{
case User.Guest:
break;
}
Here UserType is a string and User is enum. 这里的UserType是一个字符串,而User是枚举。 It worked for me.
它为我工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.