【发布时间】:2015-02-07 12:06:12
【问题描述】:
我的代码在编译时抛出了名义上的异常。我不明白为什么会发生这种情况,因为经过广泛搜索后,错误发生的原因似乎只有在没有退出返回语句的情况下存在,但我认为我的代码是完全包容的。
bool CheckExisting()
{
Account loginAcc = new Account();
string path = Application.StartupPath.ToString() + "\\Customers";
int fCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length;
for(int i = 0;i<fCount;i++)
{
String[] filePaths = Directory.GetFiles(Application.StartupPath + "\\Customers\\");
XmlDocument xmlFile =new XmlDocument();
xmlFile.Load(filePaths[i]);
foreach(XmlNode node in xmlFile.SelectNodes("//Account"))
{
string firstName = node.SelectSingleNode("FirstName").InnerText;
string lastName = node.SelectSingleNode("LastName").InnerText;
string address1 = node.SelectSingleNode("Address1").InnerText;
string address2 = node.SelectSingleNode("Address2").InnerText;
string postCode = node.SelectSingleNode("Postcode").InnerText;
string telePhone = node.SelectSingleNode("Telephone").InnerText;
string mobile = node.SelectSingleNode("Mobile").InnerText;
Account newAcc = new Account();
newAcc.firstName = firstName;
newAcc.lastName = lastName;
newAcc.address1 = address1;
newAcc.address2 = address2;
newAcc.postCode = postCode;
newAcc.telephone = telePhone;
newAcc.mobile = mobile;
loginAcc = newAcc;
}
if(txtFirstName.Text == loginAcc.firstName && txtLastName.Text == loginAcc.lastName)
{
return true;
}
else
{
return false;
}
return false;
}
}
【问题讨论】:
-
如果我正确计算您的括号,您需要在您的
for循环之外再添加一个return。喜欢;return false; } return false;最后。 -
如果你修复了缩进,阅读你的代码会容易得多。
-
@SonerGönül 你会的。不能保证
fCount在Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length之后为 != 0。 -
我的猜测是,您的意思是最终的
return false超出了最外层循环的范围。 -
很多 cmets 都是对的,而且我会提前将最后一个
return false;放在括号中。嗬!抱歉这个愚蠢的错误,但谢谢大家!
标签: c# for-loop return return-value