变量:
private string filePath1 = null;
private string filePath2 = null;
private string filePath3 = null;
private string filePath4 = null;
private string filePath5 = null;
private string filePath6 = null;
private string filePath7 = null;
private string filePath8 = null;
private string filePath9 = null;
private string filePath10 = null;
Run Code Online (Sandbox Code Playgroud)
当前 If 语句
if (string.IsNullOrEmpty(filePath1))
{
errors.Add("File Not Attached");
}
if (string.IsNullOrEmpty(filePath2))
{
errors.Add("File Not Attached");
}
....
Run Code Online (Sandbox Code Playgroud)
题:
对于每个变量,而不是有多个 if 语句。如何创建 1 个 if 语句来遍历所有这些变量?
像这样的东西:
if (string.IsNullOrEmpty(filePath + range(1 to 10))
{
errors.Add("File Not Attached");
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Reflection. 对于这种情况,这显然是不鼓励的,因为其他答案提供了更好的解决方案,只是想向您展示它可以按照您希望的方式完成(这并不意味着它是正确的方法)
public class Test
{
private string filePath1 = null;
private string filePath2 = null;
private string filePath3 = null;
}
Run Code Online (Sandbox Code Playgroud)
用法:
Test obj = new Test();
//loop through the private fields of our class
foreach (var fld in obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.Name.StartsWith("filePath"))) // filter
{
if (string.IsNullOrEmpty(fld.GetValue(obj) as string))
{
errors.Add("File Not Attached in variable: " + fld.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
在几乎所有使用具有不同编号后缀的变量的情况下,您确实应该使用集合(数组、列表等)。这是其中一种情况。我将使用此答案的列表,但任何集合就足够了。
private List<string> filePaths = new List<string>()
{
"path1",
"path2",
"path3",
"path4"
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用循环来迭代您的列表:
foreach (string path in filePaths)
{
if(String.IsNullOrEmpty(path))
errors.Add("File not attached");
}
Run Code Online (Sandbox Code Playgroud)