我可以在多个情况下使用相同的变量而无需多次写入它们吗? 例如
switch(a)
{
case 1:
ans = string.Format("someString {0}, {1}, {2}", var1, var2, var3);
case 2:
ans = string.Format("anotherString {0}, {1}, {2}", var1, var2, var3);
case 3:
ans = string.Format("thirdString {0}, {1}, {2}", var1, var2, var3);
}
我只能在一个地方写变量var1,var2和var3吗? 谢谢。
答案 0 :(得分:7)
那么当您要在每个格式中插入相同的值时,只有格式在改变吗?
然后仅在switch
中选择格式,然后执行字符串操作。在其后设置一次格式。
string fmt="";
switch(a)
{
case 1:
fmt = "someString {0}, {1}, {2}";
case 2:
fmt = "anotherString {0}, {1}, {2}";
case 3:
fmt = "thirdString {0}, {1}, {2}";
}
ans = string.Format(fmt, var1, var2, var3);
答案 1 :(得分:1)
我会写一个Dictionary<int,string>
,让代码更清晰。然后只需放置一次var1
,var2
,var3
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "someString");
dict.Add(2, "anotherString");
dict.Add(3, "thirdString");
string result = string.Empty;
if (dict.ContainsKey(a))
result = string.Format("{0} {1}, {2}, {3}", dict[a], var1, var2, var3);
编辑
感谢@mjwills建议
TryGetValue
会比ContainsKey
快,因为ContainsKey
需要进行两次搜索以获取值,而TryGetValue
只需进行一次
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "someString");
dict.Add(2, "anotherString");
dict.Add(3, "thirdString");
string ans = string.Empty;
string key = string.Empty;
if (dict.TryGetValue(a, out key))
ans = string.Format("{0} {1}, {2}, {3}", key, var1, var2, var3);
答案 2 :(得分:0)
var temp = string.Format(" {0}, {1}, {2}", var1, var2, var3);
switch (a)
{
case 1: ans = "someString" + temp; break;
case 2: ans = "anotherString" + temp; break;
case 3: ans = "thirdString" + temp; break;
}
Visual Studio 2015或更高版本中更短,可读性更差的替代方案:
if ((uint)--a < 3)
ans = $"{new[] { "someString", "anotherString", "thirdString" }[a]} {var1}, {var2}, {var3}";