Sky*_*Sky 0 c# for-loop return return-value
编译时,我的代码抛出了名义上的异常.我不明白为什么会发生这种情况,因为在广泛搜索之后,错误发生的原因似乎只有当条件存在且没有退出返回语句时,我认为我的代码是完全包容的.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
你的代码是有效的:
bool CheckExisting()
{
// Some setup code
for (int i = 0; i < fCount; i++)
{
// Code which isn't terribly relevant
return ...;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,C#5语言规范部分8.8.3讨论了for语句结束的可达性:
for如果至少满足下列条件之一,则可以访问语句的结束点:
- 该
for语句包含break退出for语句的可访问语句.- 该
for语句是可达的,并且存在for-condition并且没有常量值true.
后一种情况在这种情况下是正确的,因此for语句的结尾是可达的......这就是方法的结束.具有非void返回类型的方法的结尾永远不可访问.
请注意,即使人类可以检测到您永远无法到达for语句的末尾,也是如此.例如:
bool Broken()
{
for (int i = 0; i < 5; i++)
{
return true;
}
// This is still reachable!
}
Run Code Online (Sandbox Code Playgroud)
我们知道循环将始终至少执行一次,但语言规则不会 - 因此语句的结尾是可达的,并且您得到编译时错误.
| 归档时间: |
|
| 查看次数: |
567 次 |
| 最近记录: |