8

为什么这个 swich 语句不起作用,给出错误:

switch 表达式或 case 标签必须是 bool、char、string、integral、enum 或相应的可空类型

代码:

 switch (btn.BackColor)
 {
     case Color.Green:
         break;
     case Color.Red:
         break;
     case Color.Gray:
         break;
 }
4

4 回答 4

8

The error in in itself is self explanatory. it it telling you that switch expression must be ofone of these types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. or as the C# language specification suggests

exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types.

And you can see that BackColor is returning your a type here and it is not satisfying any of the above rules, hence the error.

you can do it like this

switch (btn.BackColor.Name)
{
   case "Green":
      break;
   case "Red":
      break;
   case "Gray":
      break;
}
于 2013-08-16T17:18:46.857 回答
6

The problem is you can't use a Color in a switch statement. It must be one of the following types, a nullable version of one of the types, or or convertible to one of these types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string

From the C# language spec, 8.7.2:

• Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types.

In your case, you could work around this by using strings, or just using a set of if/else statements.

于 2013-08-16T17:20:09.330 回答
3

You can't switch on BackColor because it's not an integral type.

You can only switch on integer types, enums (which are effectively integer types) and chars and strings.

You will need to find a property of BackCOlor that is unique (such as the Name) and switch on that.

于 2013-08-16T17:20:24.813 回答
2

正如其他答案所指出的,在语句System.Drawing.Color中不是可用的类型。是一种有趣的类型,因为它在代码中的行为类似于枚举,但那是因为它对 each 有一个静态属性,它是一种枚举类型。因此,当您在代码中看到时,这是该类在幕后所做的事情:switchColorSystem.Drawing.KnownColorColor.GreenColor

public static Color Green
{
  get
  {
    return new Color(KnownColor.Green);
  }
}

了解这些信息后,您可以编写如下代码以BackColor在开关中使用该属性:

if (btn.BackColor.IsKnownColor)
{
    switch (btn.BackColor.ToKnownColor())
    {
        case KnownColor.Green:
            break;
        case KnownColor.Red:
            break;
        case KnownColor.Gray:
            break;
    }
}
else
{
    // this would act as catch-all "default" for the switch since the BackColor isn't a predefined "Color"
}
于 2013-08-16T18:06:05.773 回答