如何根据情况返回不同类型的值?

netbooting 2013-05-03 04:06:56

public static int Sum(int a, int b)
{
int sumTotal;

try
{
sumTotal = checked(a + b);
}
catch (OverflowException)
{
sumTotal = -1; // 当求和溢出时,能不能返回一个特殊值进行提示,如“Error”
}
return sumTotal;
}
...全文
124 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
netbooting 2013-05-03
  • 打赏
  • 举报
回复
引用 2 楼 gomoku 的回复:
抛出异常比较合理。 也可以用int?返回,或额外参数: int? Sum(int a, int b){} int Sum(int a, int b, ref bool overflowed){}

    // 改成这样的了
    public static int? Sum(int a, int b)
    {
        int? sumTotal;

        try
        {
            sumTotal = checked(a + b); 
        }
        catch (OverflowException)
        {
            sumTotal = null;
        }
        return sumTotal;
    }
全栈极简 2013-05-03
  • 打赏
  • 举报
回复
 public static int Sum(int a, int b, out string msg)
    {
        int sumTotal;
 
        try
        {
            sumTotal = checked(a + b); 
            msg="OK";
        }
        catch (OverflowException)
        {
            msg="Error";
            sumTotal = -1; // 当求和溢出时,能不能返回一个特殊值进行提示,如“Error”
        }
        return sumTotal;
    }
MrYangkang 2013-05-03
  • 打赏
  • 举报
回复
可以先返回string ,调用方法之后判断返回的值是什么
gomoku 2013-05-03
  • 打赏
  • 举报
回复
抛出异常比较合理。 也可以用int?返回,或额外参数: int? Sum(int a, int b){} int Sum(int a, int b, ref bool overflowed){}
bdmh 2013-05-03
  • 打赏
  • 举报
回复
sumTotal是int,怎返回字符串,你可以自定定一个其他的变量,或者错误类型

111,097

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧