本文介绍了C#错误:不是所有的代码路径返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明在另一个类中的方法,它有一个错误并不是所有的代码路径返回值

I have declared a method in another class and it has an error "not all code paths return a value"

我想它返回一个true或false值到主程序。

I would like it to return a true or false value to the main program.

但是,当我宣布我的方法,公共静态无效,另一个错误产生,返回关键字后面不得通过对象的表情。

But when I declare my method, public static void, another error produces, a return keyword must not be followed by an object expression.

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;
                }
            }
        }
    }
}


推荐答案

您的方法 SearchFiles 只返回一个值,如果 isIdentical 。如果是真正,该方法不会返回

Your method SearchFiles only returns a value if isIdentical is false. If it's true, the method never returns.

要删除此错误,写的是这样的:

To remove this error, write something like this:

public static Boolean SearchFiles(string path1, string path2)
{
    // do some work to assign a value to isIdentical
    if (isIdentical == false)
    {
        return false;
    }
    else
    {
        return true;
    }
}

要你的第二个问题:如果你宣布你的方法公共静态无效你绝不能收益任意值。 无效意味着该方法不会给你任何东西。

To your second question: If you declare your method as public static void you must not return any value. void means that the method will not give you anything back.

您可能想看看这个: , 。特别是关于返回值的部分。

You might want to have a look at this: Methods (C# Programming Guide), especially the part about return values.

编辑:既然你有你的的if / else 的foreach 循环,你需要的东西是这样的:

Since you have your if / else in a foreach loop, you need something like this:

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;
}

这篇关于C#错误:不是所有的代码路径返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 09:41