2013-08-16 45 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" 
}