如何摆脱此错误:并非所有代码路径都返回值?

编程入门 行业动态 更新时间:2024-10-26 12:30:43
本文介绍了如何摆脱此错误:并非所有代码路径都返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 int search(string [][]mat, int n, string x){ //set indexes for top right element for(int i = 0; i<n; i++) { for(int j = n-1; j>=0; j--) { if ( mat[i][j] == x ) { Debug.Log(x +""+"Found at "+i +" "+j); // int[] n2 = new int[] {2, 4, 6, 8}; // int [] xyz = new int [] {i, j}; return i; } } }}

如何摆脱这个错误:不是所有的代码路径都返回一个值?

How to get Rid of this error: not all code paths return a value?

错误:*Assets/Scripts/Chess/Bishop.cs(237,22):错误 CS0161:`Bishop.search(string[][], int, string)':并非所有代码路径都返回值*

推荐答案

如果找不到 x,请计算出您希望发生的情况,并在方法结束时返回该结果.例如:

Work out what you want to happen if you never find x, and return that at the end of the method. For example:

// Fixed naming conventions and indentation... // Why do we need n here at all? Why not just use the length of the array? int Search(string[][] mat, int n, string x) { //set indexes for top right element for (int i = 0; i < n; i++) { // Why are we looking backwards here? for (int j = n - 1; j >= 0; j--) { if (mat[i][j] == x) { // More readable formatting... Debug.Log(string.Format("{0} found at {1}, {2}", x, i, j)); return i; } } } // Not found: return -1 to indicate failure. Or you could throw an exception return -1; }

更一般地说:编译器错误消息在这里相当清楚 - 有一种方法可以让您在不返回任何内容的情况下到达方法的末尾.值得退后一步,试着想想为什么你不能自己解决这个问题.您是否足够注意编译器错误消息?在所有情况下,您是否已经完成了该方法可能做的所有事情?下次你怎么能更好地处理这个问题?

More generally: the compiler error message was reasonably clear here - there was a way that you could get to the end of the method without returning anything. It's worth taking a step back and trying to think about why you couldn't work this out yourself. Did you pay enough attention to the compiler error message? Had you though through everything the method might do, in all situations? How could you handle this better next time?

更多推荐

如何摆脱此错误:并非所有代码路径都返回值?

本文发布于:2023-11-10 01:17:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573961.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   返回值   错误   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!