C#错误:并非所有代码路径都返回一个值

Nul*_*ion 0 c#

我在另一个类中声明了一个方法,它有一个错误"并非所有代码路径都返回一个值"

我希望它返回主程序的真或假值.

但是当我声明我的方法时,public static void会产生另一个错误,返回关键字后面不能跟一个对象表达式.

public class FileSearch
{
    public static Boolean SearchFiles(string path1, string path2)
    {
        bool isIdentical = false;
        string content1 = null;
        string content2 = null;

        DirectoryInfo d1 = new DirectoryInfo(path1);
        DirectoryInfo d2 = new DirectoryInfo(path2);

        foreach (FileInfo f1 in d1.GetFiles("*.txt", SearchOption.AllDirectories))
        {
            foreach (FileInfo f2 in d2.GetFiles("*.txt", SearchOption.AllDirectories))
            {
                content1 = (File.ReadAllText(f1.DirectoryName + "\\" + f1));
                content2 = (File.ReadAllText(f2.DirectoryName + "\\" + f2));

                isIdentical = content1.Equals(content2, StringComparison.Ordinal);

                if (isIdentical == false)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ger*_*rmi 13

SearchFiles如果isIdentical是,您的方法只返回一个值false.如果是true,则该方法永远不会返回.

要删除此错误,请执行以下操作:

public static Boolean SearchFiles(string path1, string path2)
{
    // do some work to assign a value to isIdentical
    // note that it would be idiomatic to just write "return isIdentical;" in this case
    // I keep it explicitly here for demonstration purposes 
    if (isIdentical == false)
    {
        return false;
    }
    else
    {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于你的第二个问题:如果你宣布你的方法,public static void你必须没有return任何价值.void意味着该方法不会给你任何回报.

您可能希望看一下:方法(C#编程指南),尤其是关于返回值的部分.

编辑:因为你有if / else一个foreach循环,你需要这样的东西:

public static Boolean SearchFiles(string path1, string path2)
{
    foreach(var item in collection)
    {
        // do some work to assign a value to isIdentical
        if (isIdentical == false)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // in case the collection is empty, you need to return something
    return false;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ton 9

如果if条件不正确,则需要返回一些内容

你可以试试这个

return isIdentical 
Run Code Online (Sandbox Code Playgroud)

并删除你的if语句

所以它看起来像这样

public class FileSearch
{
        public static Boolean SearchFiles(string path1, string path2)
        {
            //Do your other work here
            return isIdentical ;
        }
}
Run Code Online (Sandbox Code Playgroud)