2013-08-16 794 views

回答

6

的错误:

A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type

代码是自我解释的。它告诉你switch表达式必须是这些类型中的一个:sbyte,byte,short,ushort,int,uint,long,ulong,char,string。或C#语言规范建议

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.

而且你可以看到,背景色,这里的返回类型和它没有任何满足上述规则,因此错误。

,你可以做这样的

switch (btn.BackColor.Name) 
{ 
    case "Green": 
     break; 
    case "Red": 
     break; 
    case "Gray": 
     break; 
} 
6

问题是你不能在switch语句中使用Color。它必须是以下类型之一,该类型之一的可空版本,或或可转换为这些类型之一:sbytebyteshortushortintuintlongulongcharstring

从C#语言规范,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.

在你的情况,你可以解决此通过使用字符串,或者只是使用一组if/else语句。

3

您不能打开BackColor,因为它不是整数类型。

您只能切换整数类型,枚举(实际上是整数类型)以及字符和字符串。

您需要找到属于BackCOlor的唯一属性(例如Name)并将其打开。

2

正如其他答案指出的,System.Drawing.Color不是switch声明中的可用类型。 Color是一个有趣的类型,因为它的行为类似于代码中的枚举,但这是因为它具有每个System.Drawing.KnownColor的静态属性,这是一个枚举类型。所以,当你看到代码Color.Green,这里是什么Color类是做幕后:

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