如何在C#中退出子功能? [英] How to exit sub-function in C#?

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

问题描述

我有一个返回类型的子函数,它不是void(例如:int,double,...),我想在任何条件不正确时退出该函数,例如:



  private   int  f(  int  x)
{
if (x == 1
{
return 2 * x;
}
其他
{
// < span class =code-comment>退出此函数???
}
}





如何做到这一点?谢谢。

解决方案

  private   int  f( int  x)
{
if (x == 1
{
return 2 * x;
}
其他
{
返回 0 ;
// 退出此函数???
}
}


你不能在没有返回值的情况下退出函数



你可以使用默认值(或者)返回类型的一些定义值以退出函数





  private   int  f( int  x)
{
if (x == 1
{
返回 2 * x;
}
其他
{
返回 default int );
// 退出此函数???
}
}







如果是类型你可以使用默认(类型);

如果它是 referece 你可以使用的类型 return null


有几种方法可以做到这一点



方法1 - 返回NULL(您需要将返回类型int更改为int?)

  private   int ? f( int  x)
{
if (x == 1
{
return 2 * x;
}
其他
{
返回 null ; // 退出此功能
}
}





方法2 - 您可以设置一个代表错误条件的默认值。



<前lang =cs> 私人 int f ( int x)
{
if (x == 1
{
return 2 * x;
}
其他
{
返回 -1 ; // 使用默认值退出此函数,在调用函数中,您将检查它是否为-1。
}
}





方法3 - 你可以创建TryParse类函数,其中返回类型是bool和一个参数出去了。


I have a sub-function with return type which is not "void" (e.g: int, double,...), I want to exit that function when any condition is incorrect, e.g:

private int f(int x)
{
     if (x==1)
     {
           return 2*x;
     }
     else
     {
           // exit this function???
     }
}



How to do this? Thanks.

解决方案

private int f(int x)
       {
           if (x == 1)
           {
               return 2 * x;
           }
           else
           {
               return 0;
               // exit this function???
           }
       }


You cannot exit the function without returning a value

you can use the default value (or) some defined value of the return type to exit the function


private int f(int x)
       {
           if (x == 1)
           {
               return 2 * x;
           }
           else
           {
               return default(int);
               // exit this function???
           }
       }




If it is a value type you can use default(Type);
if it is referece type you can use return null


There are couple of ways you can do that

Method 1 - Return NULL (you will need to change the return type int to int?)

private int? f(int x)
{
     if (x==1)
     {
           return 2*x;
     }
     else
     {
           return null;// exit this function
     }
}



Method 2 - You can set a default value that will represent incorrect condition.

private int f(int x)
{
     if (x==1)
     {
           return 2*x;
     }
     else
     {
           return  -1; // exit this function with a default value and in caller function you will check if it is -1.
     }
}



Method 3 - You can create TryParse kind functions where return type is bool and one parameter is out.


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

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