是否可以在foreach循环中获取元素变量名称?我已经尝试过nameof(v),但似乎没有用。见下文:
//check for blank answer boxes and set flag for validation
foreach (string v in new object[] { answer3, answer4, answer5, answer6b, answer11, answer12, answer13b, answer14c, answer18, answer20 })
{
if (string.IsNullOrWhiteSpace(v))
{
s1.Flag = true;
s1.FlagContent += $"Blank answer box: {nameof(v)}. ";
}
}
例如,如果answer3为空或包含空白,则s1.Flag设置为true,而s1.FlagContent设置为“空白答案框:answer3”。
答案 0 :(得分:2)
您要的内容是不可能的。而且,当您考虑到给定对象可以由任意数量的变量(所有变量可能具有不同的名称)引用时,这种想法甚至毫无意义。
处理这种情况的典型方法是将答案存储在字典中,而不是给它们单独的变量。如果您绝对需要将它们放在单独的变量中,则可以将它们转换为字典,如下所示:
var dictionary = new Dictionary<string, string>
{
{ "answer1", answer1 },
{ "answer2", answer2 },
{ "answer3", answer3 },
{ "answer4", answer4 },
{ "answer5", answer5 }
};
然后问题很简单:
foreach (var item in dictionary)
{
if (string.IsNullOrWhiteSpace(item.Value))
{
s1.Flag = true;
s1.FlagContent += $"Blank answer box: {item.Key}.";
}
}
答案 1 :(得分:1)
使用字典:
string answer3 = "bla";
string answer4 = null;
string answer5 = "";
var answers = new Dictionary<string,string>();
answers.Add( nameof(answer3), answer3 );
answers.Add( nameof(answer4), answer4 );
answers.Add( nameof(answer5), answer5 );
foreach( var v in answers )
{
if (string.IsNullOrWhiteSpace(v.Value))
{
s1.Flag = true;
s1.FlagContent += $"Blank answer box: {v.Key}. ";
}
}