缩短“if,else”函数的代码
我有一个最大值为“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...
}
是否有在较短的方式做到这一点的方法?
您可以使用List<string>
和索引它Slider.Value
:
List<string> list = new List<string>() { "Text1", "Text2", ... , "TextN" };
Label.Text = list[Slider.Value];
利用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;
}
哇什么快速的答案! :O – HitomiKun
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[]
。
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..
}
延长滑块和名称属性添加到它。
Label.Text = Slider.Name;
为什么不定义一个值的数组,只是索引到这个数组?
private String[] values = new String[9] {"Value1", "Value2", ... , "Value9"};
private void Slider_Scroll(object sender, EventArgs e)
{
Label.Text = values[Slider.value];
}
这是一个非常好的解决方案,现在就使用它。感谢所有快速答案! – HitomiKun
我会利用数组:
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在手。
心连心
马里奥
你试过switch语句? – Nithesh
没有。就像我说的那样,我只能想到那个时候显示的方法。我对C#还很陌生。 – HitomiKun