如何退出此功能 [英] How do I exit this function

查看:119
本文介绍了如何退出此功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

i有这段代码

hello,
i have this piece of code

<pre>public student dequeue()
        {
            if (size > 0)
            {
                size--;
                return List.removeBeginning();
            }
            else
            {
                return ("nothing to dequeue");
                
            }
        }







}



我需要一种方法来返回不同于声明的类型的东西,在我的情况下,我需要返回一个字符串,我的函数有学生类型



我尝试了什么:



我试图使用return null但它会刹车我的代码。




}

I need a way to return something with a different type than declared, in my case I need to return a string and my function has "student" as type

What I have tried:

I tried to use return null but it brakes my code.

推荐答案

您必须返回与方法定义中声明的对象类型相同的对象。因此,在上述情况下,您必须返回 student 对象。如果没有找到数据,您可以返回 null 或空学生对象。调用者有责任检查返回项目的有效性。
You must return the same type of object as you declared in your method definition. So in the above case you must return a student object. You can return null or an empty student object if no data is found. It is the responsibility of the caller to check the validity of the returned item.


替代Richard的 - 非常准确 - 建议只返回有效值。如果没有任何要出列的内容,则抛出异常:

And alternative to Richard's - very accurate - suggestion is to only return valid values. If there is nothing to Dequeue, you throw an exception:
public Student Dequeue()
   {
   if (size <= 0) throw new ApplicationException("Tried to Dequeue when the Queue was already empty");
   size--;
   return List.RemoveBeginning();
   }


另一种选择是让你的函数返回bool并使用out参数返回Student。如果成功,则设置学生并返回true,否则返回false。然后调用代码检查函数是返回true还是false。这就是int.TryParse这样的函数的工作方式。



Another option is to have your function return "bool" and use an "out" parameter to return the Student. If it succeeds you set the student and return true, otherwise return false. The calling code then checks if the function returned true or false. This is how functions like int.TryParse work.

public bool dequeue(out student student)
{
    if (size > 0)
    {
        size--;
        student = List.removeBeginning();
        return true;
    }
    else
    {
        student = null;
        return false;
    }
}





使用





usage

student s;

if (dequeue(out s))
{
    // s will have a value
}


这篇关于如何退出此功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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