简体   繁体   English

如何修复错误 CS0161; 不是所有的代码路径都返回一个值 c# 吗?

[英]How to fix Error CS0161; not all code path return a value c#?

I'm new to c# and I'm currently working on a program that reads the path of a textfile and then displays the longest word in that file.我是 c# 的新手,目前正在开发一个读取文本文件路径然后显示该文件中最长单词的程序。 This is my code:这是我的代码:

        static void Main(string[] args)
        {
            Console.WriteLine("Enter the path for a text file: ");
            var path = Console.ReadLine();
            Console.WriteLine(LongestWord(path));
        }

        public static string LongestWord(string path) 
        {
            var characters = new char[] { ' ', '.', ',', ';', '?', '\n', '\r' };
            var content = File.ReadAllText(path);
            var words = content.Split(characters);
            var list = new List<int>();
            if (File.Exists(path))
            {
                foreach (var word in words)
                {
                    list.Add(word.Length);
                }
                int max = list.Max();
                for (int i = 0; i < words.Length; i++)
                {
                    var count = words[i].ToCharArray();
                    if (count.Count() == max)
                    {
                        return words[i];
                    }
                }
            }
            else
            {
                return "You entered a file that could not be located";
            }

        }

As you see I tried making "Longestword" a method that I could use anywhere.如您所见,我尝试使“Longestword”成为一种我可以在任何地方使用的方法。 This is when I get the named error.这是我得到命名错误的时候。 The code works otherwise if I use it in the same Main class.如果我在同一个 Main class 中使用代码,则代码会以其他方式工作。

I tried several "if" statements and exceptions but none of them seem to solve the problem.我尝试了几个“if”语句和异常,但似乎都没有解决问题。

The problem here is that there is a path of execution where no return statements are encountered.这里的问题是有一个执行路径没有遇到 return 语句。 Specifically where the file is count, and opened, but then the if statement at the second for loop is never evaluated to true.特别是在文件计数和打开的位置,但是第二个 for 循环中的 if 语句永远不会被评估为 true。

Now under normal execution, this should never happen, but this is technically possible.现在在正常执行下,这应该永远不会发生,但这在技术上是可行的。 One way to resolve this is to throw an exception after this loop.解决此问题的一种方法是在此循环后抛出异常。 But the best thing is to resolve the logic.但最好的办法是解决逻辑。

If you are comfortable using LINQ, the whole of:如果您愿意使用 LINQ,则:

            foreach (var word in words)
            {
                list.Add(word.Length);
            }
            int max = list.Max();
            for (int i = 0; i < words.Length; i++)
            {
                var count = words[i].ToCharArray();
                if (count.Count() == max)
                {
                    return words[i];
                }
            }

Can be replaced with: return words.OrderByDescending(w => w.Length).First();可以替换为: return words.OrderByDescending(w => w.Length).First();

Otherwise a default value should be returned, something like null or the last element of the list.否则应返回默认值,例如null或列表的最后一个元素。

Some other notes: When using a string or an array, you can use the .Length property instead of the Linq Extension .Count() .其他一些注意事项:使用字符串或数组时,可以使用.Length属性代替 Linq Extension .Count() .Length just retrieves the stored value (quickly), but .Count() would loop through the string/array every time (although Linq has optimizations to avoid this type of extra work) .Length只是检索存储的值(快速),但.Count()每次都会循环遍历字符串/数组(尽管 Linq 已进行优化以避免此类额外工作)

You have no return statement after if (count.Count() == max) . if (count.Count() == max)之后没有返回语句。 You shall also check if file is not empty.您还应检查文件是否不为空。 If file doesn't exists it's better to throw an exception.如果文件不存在,最好抛出异常。 You are trying to read file before checking if it exists, if the file doesn't exists you will get exception.您在检查文件是否存在之前尝试读取文件,如果文件不存在,您将获得异常。

static string? LongestWord(string path) {
    var characters = new char[] { ' ', '.', ',', ';', '?', '\n', '\r' };
    var list = new List<int>();
    string result = string.Empty;
    if (File.Exists(path)) {
        var content = File.ReadAllText(path);
        if(content.Length > 0) {
            var words = content.Split(characters);
            foreach (var word in words) {
                list.Add(word.Length);
            }
            int max = list.Max();
            for (int i = 0; i < words.Length; i++) {
                var count = words[i].ToCharArray();
                if (count.Count() == max) {
                    result = words[i];
                }
            }
            return result;
        } else {
            return null; //Or throw exception
        }
    } else {
        throw new FileNotFoundException();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM