并非所有code路径返回一个值(布尔变量)
我在创造经验的消息服务的应用程序的过程。不过,我穿过我以前就遇到一个错误绊倒了。这里是我的方法:
I'm in the process of creating a messaging service application for experience. However, I've stumbled across an error I've encountered before. Here is my method:
bool userExists(string pcName)
{
string[] files = Directory.GetFiles(usersFile);
foreach (string fileName in files)
{
if (fileName == pcName)
{
return true;
}
else
{
return false;
}
}
}
正如你所看到的,这个方法返回一个肯定或者如果用户的TXT文件的文件夹中不存在的答案。现在,对我来说,所有的code路径返回一个值。这是有道理的,显然编译器不会想的一样,因为我得到的布尔userExists抱怨,并非所有code路径返回一个值的误差。我怎样才能解决这个问题?
谢谢!
As you can see, this method returns a yes or no answer on if the user's txt file exists in the folder. Now, to me, all code paths return a value. It makes sense, obviously the compiler doesn't think the same because I get an error on "bool userExists" complaining that not all code paths return a value. How can I fix this issue? Thanks!
如果例如,文件列表是空的,会发生什么?结果
编译器到达而没有碰到return语句函数的结尾,这就是它告诉你。
What happens if for example, the list files is empty?
The compiler reach the end of the function without hitting a return statement, that's what it tells you.
写你的code的好方法是:
The good way to write your code is:
bool userExists(string pcName)
{
string[] files = Directory.GetFiles(usersFile);
foreach (string fileName in files)
{
if (fileName == pcName)
{
return true;
}
}
return false;
}
和它可能是熟悉的LINQ的时刻:
And it could be the moment to become familiar with Linq:
bool userExists(string pcName)
{
return Directory.GetFiles(usersFile)
.Any(file => file == pcName);
}