不是所有的代码路径都返回类中的值 [英] not all code paths return a value in class

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

问题描述

我知道这是一个问题谁被问过,但我无法解决这个



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

中的值

  class Class1 
{


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

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



} //方法colordetector



} // class1


解决方案

让我们看看你的班级...



>



你已经创建了一个方法..并已定义(在方法签名中)该类返回一个 System.Drawing.Color



现在,看看这个方法的代码 c> if 检查。



但是如果 name 是black,会发生什么?会发生什么呢?它不会通过每个这三个if检查然后做什么?



代码需要处理发现不是颜色的情况。



解决方案:




  • 如果未找到/处理传入的颜色,则抛出异常。



如果未找到/处理传入的颜色,则返回默认颜色。

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天全站免登陆