[英]How to combine two strings into the name of another string and call that string?
有什么方法可以將這段代碼簡化為幾行,我有一個帶有字符串 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; }
}
可能這可以幫助您減少 LOC。
public static void setCategorySeq(string lucio, string textValue)
{
string[] seq = new string[16];
for (int i = 0; i <= 15; i++)
{
if (lucio == i.ToString())
seq[i] = textValue;
}
}
也許這段代碼適合你:
static Dictionary<string, string> seq = new Dictionary<string, string>(); public static void setCategorySeq(string lucio, string textValue) { seq[lucio] = textValue; } public static string setCategorySeq(string lucio) { if (seq.ContainsKey(lucio)) return seq[lucio]; return null; }
只用字典
var lookup = new Dictionary<string,string>();
然后在字典中設置一個條目
lookup[lucio] = textValue;
並訪問它
Console.WriteLine(lookup[lucio])
如果你真的想驗證字符串是 0 到 15 之間的值,那么首先解析它並驗證它並使用一個以整數作為鍵的字典
var lookup = new Dictionary<int,string>();
// Using C# 7 notation
if(int.TryParse(lucio, var out lucioInt) && lucionInt > 0 && lucioInt < 16){
lookup[lucioInt] = textValue;
}
我希望這可能會有所幫助
public static void setCategorySeq(string lucio, string textValue)
{
var seq = new string[15];
int noOfsequence=15;
for(int i=0;i<noOfsequence;i++)
{
if(lucio==i.ToString())
{
seq[i] = textValue;
break;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.