简体   繁体   中英

How can I using xor to make my code shorter

I have three checkbox in windows form application bold,italic and underline

when I change check I want the text in label to change to one of these and if I check two of the I want them to active together I do long code for this using if...else but I want shorter code using xor ^ I heard it is shorter but I do not know how

I'd use 3 ifs:

aLabel.Text = "";
if(xCheckBox.Checked)
  aLabel.Text += "x, ";
if(yCheckBox.Checked)
  aLabel.Text += "y, ":
if(zCheckBox.Checked)
  aLabel.Text += "z, ";
aLabel.Text = aLabel.Text.TrimEnd(' ', ',');

Because it (or some variation on it) is easy to understand..

You could put the text you want in the checkbox tag and then do;

aLabel.Text = string.Join(", ", this.Controls.OfType<CheckBox>()
.Where(cb => cb.Checked)
.Select(cb => cb.Tag));

If you have many checkboxes on the form and want this to apply to only a few either name them some pattern you can check for in the Where, or put them in a panel and call panel.Controls instead of this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM