编码风格-仅在预检查为空字符串时才连接c#字符串
本文关键字:字符串 连接 检查 风格 编码 | 更新日期: 2023-09-27 17:49:32
我是c#新手,我正在尝试连接c#中的字符串,以在文本框中显示选中的结果,然后单击按钮。我能够得到所需的输出,但代码似乎没有遵循SE中的DRY原则。
private void button1_Click(object sender, EventArgs e)
{
String result1, result2="";
if (radioButton1.Checked )
{
result1 = radioButton1.Text;
}
else if (radioButton2.Checked)
{
result1 = radioButton1.Text;
}
else if (radioButton3.Checked)
{
result1 = radioButton3.Text;
}
if (checkBox1.Checked)
{
result2 = checkBox1.Text;
}
if (checkBox2.Checked)
{
if (result2 != "")
{
result2 = result2 + "," + checkBox2.Text;
}
else
result2 = checkBox2.Text;
}
if (checkBox3.Checked)
{
if (result2 != "")
{
result2 = result2 + "," + checkBox3.Text;
}
else
result2 = checkBox3.Text;
}
textBox1.Text="You like to shop from "+ result1
+"for clothing styles like "+result2;
}
我相信应该有很多聪明的方法来做到这一点,如果有人能给我一个更好的解决方案,我将不胜感激。
这可以写成一行(如果你的复选框都包含在窗体
的控件集合中)result2 = string.Join(",", this.Controls.OfType<CheckBox>()
.Where(x => x.Checked)
.Select(c => c.Text));
如何使用String。Join和String.Format?
之类的private void button1_Click(object sender, EventArgs e)
{
String result1, result2="";
if (radioButton1.Checked )
{
result1 = radioButton1.Text;
}
else if (radioButton2.Checked)
{
result1 = radioButton1.Text;
}
else if (radioButton3.Checked)
{
result1 = radioButton3.Text;
}
List<string> choices = new List<string>();
if (checkBox1.Checked)
{
choices.Add(checkBox1.Text);
}
if (checkBox2.Checked)
{
choices.Add(checkBox2.Text);
}
if (checkBox3.Checked)
{
choices.Add(checkBox3.Text);
}
textBox1.Text=String.Format("You like to shop from {0} for clothing styles like {1}", result1, String.Join(",",choices.ToArray()));
}