枚举和开关语句

3

您好,我正在使用枚举转换为字符串并带有switch语句,但它无法正常工作。它会出现编译错误:Cannot implicitly convert type 'userControl_commontop.UserType' to 'string'

代码如下:

private void CommonTopChangesnew(string usertype)
{

    switch (usertype.Trim().ToUpper())
    {
        case UserType.NORMAL :
            hlkSAD.Enabled = false;
            hlkMRTQuery.Enabled = false;
            hlkReqViewer.Enabled = false;
            hlkSendnotif.Enabled = false;
            break;
        case UserType.POWER :
            hlkSAD.Enabled = false;
            hlkReqViewer.Enabled = false;
            hlkSendnotif.Enabled = false;
            break;
    }
}

enum UserType
{
    NORMAL,
    POWER,
    ADMINISTRATOR
}

请重新格式化您的代码片段;目前它无法阅读... - Shaul Behr
6个回答

5

枚举不是一个字符串,就像常量const int MY_VALUE = 1;也不是一个字符串。

你应该将你的字符串改成枚举:

switch ((UserType)Enum.Parse(usertype, typeof(UserType))) {
  ...
}

1
第一种选项可能行不通,因为 switch 要求 case 语句必须是常量。 - Josh
@ShaulBehr 我知道这已经过时了...但是Hari是完全正确的 - 第一个例子不会起作用。那是因为switch语句要求case是常量(虽然如果有办法绕过这个限制,我非常渴望听到它)。 - Maverick
1
@Maverick - 虽然晚了几年,但我已经确认了!我会更新我的答案。 - Shaul Behr

5
你应该尝试这个:
enum UserType
{
  NORMAL,
  POWER,
  ADMINISTRATOR
}

private void CommonTopChangesnew(string usertype)
{
  switch ((UserType)Enum.Parse(typeof(UserType), usertype, true))
  {
    case UserType.NORMAL:
      hlkSAD.Enabled = false;
      hlkMRTQuery.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
    case UserType.POWER:
      hlkSAD.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
  }
}

3
您可以使用此函数将userType参数转换为枚举值:
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

as

UserType utEnum =  Enum.Parse(UserType, userType, true);

然后你可以这样调用你的switch语句:

switch (utEnum)
    { ... }

2

你的函数接受一个字符串类型的参数,然后你使用同样的参数来比较属于枚举类型的类型。这里就产生了冲突。

你的函数应该改为:

private void CommonTopChangesnew(UserType usertype)
{

  switch (usertype)
  {
    case UserType.NORMAL :
      hlkSAD.Enabled = false;
      hlkMRTQuery.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
    case UserType.POWER :
      hlkSAD.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
  }
}

0

你不能将字符串与枚举类型进行比较。

你应该向你的方法传递一个枚举类型。


0

选项1: 将您的CommonTopChangesnew更改为接受UserType枚举作为参数

或者

选项2: 在switch块中使用Enum.Parse将您的字符串转换为UserType枚举:

(UserType)Enum.Parse(typeof(UserType), usertype)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接