如果其他条件更短,怎么写? [英] How to write if Else conditions in Shorter way ?

查看:100
本文介绍了如果其他条件更短,怎么写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以在下面观察我的代码吗'太长了......我想写得更短,帮助我任何一个人知道





can u observe my code below it' so lengthy.. I want write in Shorter way , help me any one know


int paymentType = 0;
            if (lblPayment.Text == "Credit")
            {
                paymentType = 1;
            }
            else if (lblPayment.Text == "Open Invoice")
            {
                paymentType = 2;
            }

            else if (lblPayment.Text == "COD")
            {
                paymentType = 3;
            }

            else if (lblPayment.Text == "Check")
            {
                paymentType = 4;
            }

            else if (lblPayment.Text == "Paypal")
            {
                paymentType = 5;
            }

            else if (lblPayment.Text == "Money Order")
            {
                paymentType = 6;
            }

            else if (lblPayment.Text == "Other")
            {
                paymentType = 7;
            }

推荐答案

您可以使用枚举。这样你就可以直接为paymentType赋值。



Instead of dealing with strings, you could use an enum. That way you can directly assign value to paymentType.

paymentType = (int)Enum.Parse(typeof(YourEnum),"ValueHere");







根据您在屏幕上使用的控件,你可以将它绑定到这些枚举值。更好的是,你使用 RadioButton 的集合。分配所有单选按钮的标记属性,并为所有单选按钮设置一个 CheckedChanged 事件处理程序。在处理程序中,你可以使用这样的东西:






Based on what controls you are using on screen, you could bind it to these enum values. Better still, you and use set of RadioButton. Assign Tag property of all radio buttons and have a single CheckedChanged event handler for all. In the handler, you can use something like this:

int paymentType = (int)(sender as RadioButton).Tag;


如上所述 - 更正确的方法是使用switch-case语句。





As mentioned - the more right way would be to use a switch-case-statement.


switch(lblPayment.Text)
{
   case "Credit" :
         //paste your action
         break;
}





您可以使用字典,但不能像上面描述的那样,作为字符串的翻译列表。

使用全局静态列表(枚举类型或字典)作为所有与支付方法相关的控件的来源。



You could use a dict, but not like the way described above, as translation list for a string.
Use a global static list (enum-type or dict) as source of all payment method related controls.


而不是 if 声明使用切换 [ ^ ]声明。



您可以构建自己的字典 [ ^ ]。br />


Instead of if statement use switch[^] statement.

You can build your own dictionary[^] too.

Dictionary<int,string> payTypes = new Dictionary<int,string>();

// Add some elements to the dictionary. There are no  
// duplicate keys, but some of the values are duplicates.
payTypes.Add(1, "Credit");
payTypes.Add(2, "Open Invoice");
payTypes.Add(3, "COD");
payTypes.Add(4, "Check");
//and so on...





字典类公开了几种方法,例如包含() [ ^ ],快速查找搜索值;)



Dictionary class exposes several methods, for example Contains()[^], to quickly find searched value ;)


这篇关于如果其他条件更短,怎么写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆