【发布时间】:2017-01-26 05:34:04
【问题描述】:
有什么方法可以将这段代码简化为几行,我有一个带有字符串 seq(number) 的类有 {get;set} 函数。我正在从另一个班级获得 lucio 和 textValue。
public static void setCategorySeq(string lucio, string textValue)
{
if (lucio == "0") { seq0 = textValue; }
else if (lucio == "1") { seq1 = textValue; }
else if (lucio == "2") { seq2 = textValue; }
else if (lucio == "3") { seq3 = textValue; }
else if (lucio == "4") { seq4 = textValue; }
else if (lucio == "5") { seq5 = textValue; }
else if (lucio == "6") { seq6 = textValue; }
else if (lucio == "7") { seq7 = textValue; }
else if (lucio == "8") { seq8 = textValue; }
else if (lucio == "9") { seq9 = textValue; }
else if (lucio == "10") { seq10 = textValue; }
else if (lucio == "11") { seq11 = textValue; }
else if (lucio == "12") { seq12 = textValue; }
else if (lucio == "13") { seq13 = textValue; }
else if (lucio == "14") { seq14 = textValue; }
else if (lucio == "15") { seq15 = textValue; }
}
【问题讨论】:
-
我实际上不确定我是否理解您的问题。但我认为您正在寻找的是您可以调用一个键(例如 lucio)并且您想要设置其各自的值(例如 seq)。我说的对吗?
-
你应该使用 Switch 语句来完成这种工作。
-
正如@UmairAnwaar 所提到的,switch 将是这种情况下的最佳选择,虽然我个人喜欢缩短行数,所以我会研究反射(不确定是否会更好)到“设置”一个变量的值,基于其名称作为字符串。供参考:stackoverflow.com/a/5218649/6741868
-
@KeyurPATEL 您可以通过反射设置属性,但不能通过反射设置局部变量。对于用户正在尝试做的事情,字典可能是最好的解决方案。
-
@bradgonesurfing:太好了——这肯定会有所帮助。