我想在c#中以更短的方式编写Else条件 你能不能在下面看到我的代码'如此冗长......我想以更短的方式写作,帮助我任何人都知道。我们可以使用其他任何方式来写它吗?
int paymentType;
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;
}
答案 0 :(得分:14)
请考虑使用字典:
Dictionary<string, int> lookup = new Dictionary<string, int>();
lookup.Add("Credit", 1);
lookup.Add("Open Invoice", 2);
//etc
然后:
int paymentType = lookup[lblPayment.Text];
如果字典中不存在该值,则会抛出KeyNotFoundException
。如果要在查找表中不存在该值时提供默认值或执行其他操作,可以使用TryGetValue
,如下所示:
int paymentType;
if (lookup.TryGetValue(lblPayment.Text, out paymentType)) {
//do stuff with paymentType
} else {
//handle error, paymentType is now 0.
}
答案 1 :(得分:5)
使用switch声明:
switch(lblPayment.Text)
{
case "Credit":
paymentType = 1;
break;
case "Open Invoice":
paymentType = 2;
break;
......
}
答案 2 :(得分:4)
您可以使用enum:
public enum PaymentType
{
NA,
Credit,
OpenInvoice,
COD,
Check,
Paypal,
MoneyOrder,
Other
}
int paymentType = (int)PaymentType.Credit;
编辑以添加有关如何使用此内容的更简明的说明。
如果您可以控制与标签文字进行比较的字符串,则可以执行以下操作:
int paymentType = (int)Enum.Parse(typeof(PaymentType), lblPayment.Text, true);
这假设你有enum友好的字符串,这就是为什么我规定你需要控制它们以避免空格/特殊字符等...看起来你不是那么你需要做的就是{{{在解析之前确保标签lblPayment.Text.Replace(" ", string.Empty);
与枚举标志匹配。
答案 3 :(得分:1)
只是一个想法,你可以将它存储在一个数组中,并在每个索引存储一个值
ExAr[1]="sometext";
我认为这是最短的解决方案,您只需拨打一行即可显示预存储值
string[] arr4 = new string[3];
arr4[0] = "one";
arr4[1] = "two";
arr4[2] = "three";
// Loop through all instances to find "one"
int i = 0;
while ((i = s.IndexOf('one', i)) != -1)
{
// Print out the substring.
Console.WriteLine(s.Substring(i));
// Increment the index, the index is the payment value you seek
i++;
}
答案 4 :(得分:1)
根据您在每个条件分支中需要执行的操作,您可以使用多种语言结构(switch
,三元运算符,...)。在您的情况下,您可以使用查找各种类型的汇票,将它们映射到付款类型:
var paymentTypeMap = new Dictionary<string, int>
{
{ "Credit", 1 },
{ "Open Invoice", 2 },
...
}
int paymentType;
if (paymentTypeMap.TryGetValue(lblPayment.Text, out paymentType))
{
// OK
}
else
{
// Unknown payment method
}
答案 5 :(得分:-1)
切换。
Switch / Case可以处理C#中的字符串,你知道。
那就是
switch (lblPayment.Text)
case "Credit":
paymentType = 1;
break;
case "Open Invoice":
paymentType = 2;
break;
etc.etc.etc。