并非所有的代码路径返回类的值 [英] not all code paths return a value in class

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

问题描述

我该知道是谁之前已经问了一个问题,但我无法解决这个



我想写一个类来检测并返回颜色,但我得到这个错误:不是所有的代码路径类返回一个值

 类class1 
{


公众的System.Drawing.Color colordetector(字符串名称)
{

如果(name.Contains(蓝)==真){返回的System.Drawing.Color。蓝色; }
如果(name.Contains(绿色)==真){返回System.Drawing.Color.Green; }
如果(name.Contains(红)==真){返回System.Drawing.Color.Red; }



} //方法colordetector



} // class1的


解决方案

让我们看看你的类...





所以,你装箱的方法..和定义(在方法签名)阶级返回的System.Drawing.Color



现在,看代码的的这种方法......你在做的如果检查。



但如果名称是''黑',会发生什么?那么会发生什么?它不会通过每个那三个,如果的检查,然后做什么?



中的代码需要处理的场景时,有颜色的的发现。



解决方案:




  • 抛出一个异常,如果传递的颜色没有被发现/处理

  • 返回默认颜色如果传入的颜色没有被发现/处理。


i know this a question who has been asked before , but i could not resolve this

i want to write a class to detect and return color but i get this error : not all code paths return a value in class

class Class1
{


    public System.Drawing.Color colordetector(string name)
    {

        if (name.Contains("blue") == true) { return System.Drawing.Color.Blue; }
        if (name.Contains("green") == true) { return System.Drawing.Color.Green; }
        if (name.Contains("red") == true) { return System.Drawing.Color.Red; }



    }//method colordetector



}//class1

解决方案

Lets look at your class...

So you've crated a method .. and have defined (in the method signature) that the class returns a System.Drawing.Color.

Now, looking at the code inside this method ... you're doing three if checks.

BUT what happens if name is `'black' ? what will happen then? it will not pass each of those three if-checks and then do what?

the code needs to handle the scenario when there colour is not found.

Solutions:

  • Throw an exception if the colour passed in was not found/handled.
  • Return a default colour if the colour passed in was not found/handled.

这篇关于并非所有的代码路径返回类的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆