c# - boolean 错误: “not all code paths return a value”

标签 c# compiler-errors boolean boolean-operations

我创建了一种快速测试方法来尝试检查文件及其内容,但是由于某种原因,我收到错误消息“并非所有代码路径都返回值”。据我所知,除了主要的“if”语句外,它们都可以。但是,如果我在该语句中设置了返回值,它将覆盖其他返回值。

谁能告诉我为什么会这样/解释造成错误的原因是什么?

public static bool FileCheck()
{
    string file = @"C:\Temp\test.txt";
    Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

    if (File.Exists(file) == true)
    {
        StreamReader rdr = new StreamReader(file);
        string myString = rdr.ReadToEnd();

        if (myString == null)
        {
            Console.WriteLine("File empty");
            return false;
        }
        else { Console.WriteLine(myString); return true; }
    }
}

最佳答案

如果没有其他的话

if (File.Exists(file) == true)  

如果为假,则不返回任何内容。因此,您需要在末尾添加return false。
if (File.Exists(file) == true)  
{
   ...
}

return false;  

当您的方法执行时,期望返回您定义的类型。在您的情况下,调用该方法时,应返回一个 bool(boolean) 值。当代码执行路径进入if语句时,这很好,因为它返回一个 bool(boolean) 值。如果代码未放入if中,则您的代码将不返回任何内容。那是错误。用铅笔和纸遍历代码,看看它是如何执行的。

关于c# - boolean 错误: “not all code paths return a value” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21715514/

相关文章:

c# - 如何将嵌套三元组提取到独立语句中

GoLand IDE 无法正确编译。如何设置正确的路径?

objective-c - 带有 BOOL 标志的应用程序状态

php - MySQL 全文搜索仅适用于 BOOLEAN 模式。如何获得相关性?

swift - 如何使用 Parse 子类和 User 之间的关系 - Swift

C# 文件监控

C# :Does Client machine need SQL Server installed on it while connecting to other machine having SQL Server installed on it (the Server machine)

c# - Google Sheets - 如何通过行索引获取多行数据

vbscript - VBS预期语句错误

c - 我使用 'exit(EXIT_FAILURE);' ,但随后出现错误