并非所有code路径返回一个值(布尔变量) [英] Not all code paths return a value (bools)

查看:191
本文介绍了并非所有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);
}

这篇关于并非所有code路径返回一个值(布尔变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆