我怎么打破if-else-if .....为什么它不起作用?它只是检查所有条件而不是执行任务.以下是我的代码.我已经通过断点检查了它是否符合所有条件,为什么它在满足正确条件后不会停止.即使它没有进入if活动,它只是阅读所有条件,最后什么都不做.
private void ShowHash()
{
inpic = pb_selected.Image;
Bitmap image = new Bitmap(inpic);
byte[] imgBytes = new byte[0];
imgBytes = (byte[])converter.ConvertTo(image, imgBytes.GetType());
string hash = ComputeHashCode(imgBytes);
txt_selectedText.Text = hash;
GetHash();
}
private void GetHash()
{
if (txt_sel1.Text == null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null ))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (txt_sel2.Text != null && (txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (txt_sel3.Text != null && (txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (txt_sel4.Text != null && (txt_sel5.Text == null))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
}
Run Code Online (Sandbox Code Playgroud)
我强烈怀疑问题是该Text财产永远不会出现null任何问题txt_sel*.假设这些是UI中的文本框,则更有可能的是,如果文本框中没有文本,则Text属性将返回""而不是null.这就是大多数UI框架处理空控件的方式.
我还建议首先将条件提取到局部变量:
bool hasSel1 = txt_sel1.Text != "";
bool hasSel2 = txt_sel2.Text != "";
bool hasSel3 = txt_sel3.Text != "";
bool hasSel4 = txt_sel4.Text != "";
bool hasSel5 = txt_sel5.Text != "";
if (!hasSel1 && (!hasSel2 || !hasSel3 || !hasSel4 || !hasSel5)
{
...
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,为控件提供更有意义的名称 - 具有相同前缀的变量集合,但就可读性而言,数字后缀很少是一个好主意.