2011-08-19 26 views
3

我有一個最大值爲「9」的滑塊。每個值都應改變標籤的文字。 我只能想到這個方法現在:縮短「if,else」函數的代碼

private void Slider_Scroll(object sender, EventArgs e) 
{ 
    if (Slider.Value == 0) 
     { 
      Label.Text = "Text1"; 
     } 
    else if (Slider.Value == 1) 
     { 
      Label.Text = "Text2"; 
     } 
    //...and so on... 
} 

是否有在較短的方式做到這一點的方法?

+1

你試過switch語句? – Nithesh

+0

沒有。就像我說的那樣,我只能想到那個時候顯示的方法。我對C#還很陌生。 – HitomiKun

回答

0

您可以使用List<string>和索引它Slider.Value

List<string> list = new List<string>() { "Text1", "Text2", ... , "TextN" }; 

Label.Text = list[Slider.Value];
0

利用Switch...Case而不是if..else

private void Slider_Scroll(object sender, EventArgs e) 
{ 
    var text = string.Empty; 
    Switch(Slider.Value) 
    { 
     case 0: 
      text = "text1"; 
     break; 
     case 1: 
      text = "text2"; 
     break; 
     //....go on 
    } 

    Label.Text = text; 
} 
+0

哇什麼快速的答案! :O – HitomiKun

12
switch(Slider.Value) { 
    case 0: Label.Text = "Text1"; break; 
    case 1: Label.Text = "Text2"; break; 
} 

或;使用字典:

static readonly Dictionary<int,string> labels = new Dictionary<int,string> { 
    {0, "Text1"}, 
    {1, "Text2"} 
}; 

和:

string text; 
if(labels.TryGetValue(Slider.Value, out text)) { 
    Label.Text = text; 
} 

,如果你需要根據配置在運行時查找文本詞典的方法是特別有用的(即它們不是硬編碼)。

如果你的值是連續的整數(0到9等),你也可以使用string[]

+1

+1用於字典。 – J0HN

+0

謝謝!這看起來更清晰和更快。 – HitomiKun

0

Label.Text = "Text" + (1 + Slider.Value).ToString()

+0

雖然xD我只是舉了一個例子,但這並不是我想要的。其實我想把文本的每個值都改成別的東西。 – HitomiKun

+0

我認爲「文字」+數字只是概念,真正的字符串是別的。如果沒有,您的答案可能是最好的:) – Tigran

0
Label.Text = string.Format("Text{0}",Slider.Value+1); 

如果NT默認的始終:

static reaonly Dictionary<int,string> labelMap = new Dictionary<int,string> { 
    {0, "Text1"}, {1, "Text2"}, {1, "TextValue3"} 
}; 

if(labelMap.ContainsKey(Slider.Value)) 
{ 
Label.Text = string.Format("Text{0}",labelMap [Slider.Value]); 
} 
else 
{ 
Label.Text=<defaut_value>; //or throw exception etc.. 
} 
2

延長滑塊和名稱屬性添加到它。

Label.Text = Slider.Name; 
3

爲什麼不定義一個值的數組,只是索引到這個數組?

private String[] values = new String[9] {"Value1", "Value2", ... , "Value9"}; 

private void Slider_Scroll(object sender, EventArgs e) 
{ 
    Label.Text = values[Slider.value]; 
} 
+0

這是一個非常好的解決方案,現在就使用它。感謝所有快速答案! – HitomiKun

0

我會利用數組:

string SliderLabels[] = {"Text1" 
         , "Text2" 
         , "Text3" 
         , "Text4" 
         , "Text5" 
         , "Text6" 
         , "Text7" 
         , "Text8" 
         , "Text9"}; 

private void Slider_Scroll(object sender, EventArgs e) 
{ 
    if (Slider.Value < SliderLables.length) 
    { 
     Label.Text = SliderLabels[ SliderValue ]; 
    } 

} 

請原諒錯別字或小的語法錯誤,我做沒有我的VS在手。

心連心

馬里奧