简体   繁体   English

如何缩短“if else”事件?

[英]How can I shorten the "if else" event?

how can I Write this as short as possible?我怎样才能把这个写得尽可能短? here are many more conditions.这里有更多的条件。 The purpose of the code below is to calculate the total price and display it as a message, adding the price of each selected hardware to the determined base price to the Calculate button click event.下面代码的目的是计算总价并将其显示为一条消息,将每个选定硬件的价格与确定的基本价格相加到计算按钮单击事件中。

( sorry for bad english:/ ) (抱歉英语不好:/)

decimal tabanFiyat = 500;
decimal cpuFiyat = 0;

if (rbCpuI7.Checked)
  cpuFiyat = 300;
else if (rbCpuI5.Checked)
  cpuFiyat = 200;
else if (rbCpuI3.Checked)
  cpuFiyat = 100;
else if (rbCpuR5.Checked)
  cpuFiyat = 250;
else if (rbCpuR3.Checked)
  cpuFiyat = 150;

tabanFiyat += cpuFiyat;

decimal ramFiyat = 0;

if (rbRam16.Checked)
  ramFiyat = 125;
else if (rbRam8.Checked)
  ramFiyat = 75;
else if (rbRam4.Checked)
  ramFiyat = 45;

tabanFiyat += ramFiyat;

I think this can work:我认为这可以工作:

cpuFiyat = (rbCpuI7.Checked)? 300: 
           (rbCpuI5.Checked)? 200:
           (rbCpuI3.Checked)? 100:
           (rbCpuR5.Checked)? 250:
           (rbCpuR3.Checked)? 150: 0;

tabanFiyat += cpuFiyat;
decimal ramFiyat;
ramFiyat = (rbRam16.Checked)? 125:
           (rbRam8.Checked)?   75:
           (rbRam4.Checked)?   45: 0;

tabanFiyat += ramFiyat;

Assuming those are radio buttons假设那些是单选按钮

  var radList = new List<(RadioButton, int)> {
      (rbCpuI7,300),
      (rbCpuI5,200)
      .....
   };

   var chck = radList.FirstOrDefault(x=>x.Item1.Checked);
   rbCpuI5 += chk.Item2;

if nothing is checked you will get 0如果什么都不检查你会得到 0

Assuming the.Checked property comes from some UI, the framework is likely to expose an "onChecked" event so the event handler should assign the correct value, and uncheck others if mutually exclusive.假设 .Checked 属性来自某些 UI,框架可能会公开一个“onChecked”事件,因此事件处理程序应该分配正确的值,如果相互排斥则取消选中其他值。 But you'd need to provide more details.但是您需要提供更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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