3

嗨,我正在使用带有开关的枚举转换为字符串,但它不起作用。它给出了编译错误:无法将类型“userControl_commontop.UserType”隐式转换为“字符串”

代码是:

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
}
4

6 回答 6

5

枚举不是字符串,正如常量const int MY_VALUE = 1;不是字符串一样。

您应该将字符串更改为枚举:

switch ((UserType)Enum.Parse(usertype, typeof(UserType))) {
  ...
}
于 2009-05-08T07:38:51.887 回答
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;
  }
}
于 2009-05-08T07:39:01.603 回答
3

您可以使用此函数将 userType 参数转换为枚举值:

object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

作为

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

然后您可以将您的 switch 语句称为:

switch (utEnum)
    { ... }
于 2009-05-08T07:44:34.990 回答
2

您的函数接受字符串类型的参数,然后使用相同的参数来比较属于 Enum 的类型。冲突就在这里。

您的功能应该是:

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;
  }
}
于 2009-05-08T07:40:20.603 回答
0

您不能将字符串与枚举进行比较。

您应该将 Enum 传递给您的方法。

于 2009-05-08T07:41:44.780 回答
0

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

或者

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

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

于 2009-05-08T07:42:47.740 回答