从方法返回多个结果 [英] Returning multiple results from a method

查看:22
本文介绍了从方法返回多个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 Try Catch 块和更好的错误处理来提高我的技能.

I trying to improve my skills using Try Catch blocks and better error handling.

我有一个执行常见任务的类,在本例中检索 Facebook AccessToken.如果成功,我想返回 AccessToken 字符串,如果不成功,我想返回错误消息.这两个都是字符串,所以没问题.但是在代码调用端检查返回值时,如何有效地做到这一点?

I have a class that performs a common task, in this case retrieving a Facebook AccessToken. If successful, I want to return the AccessToken string, if not I want to return an error message. These are both strings, so no problem. But when checking the return value on the calling side of the code, how can you do this effectively?

这就像我需要返回 2 个值.在尝试成功的情况下,return = true, "ACESSCODEACXDJGKEIDJ",或者如果失败,return = false, "Ooops, there was an error" + ex.ToString();

It's like I need to return 2 values. In the case of a successful attempt, return = true, "ACESSCODEACXDJGKEIDJ", or if it fails, return = false, "Ooops, there was an error" + ex.ToString();

然后检查返回值很容易(理论上).我可以考虑简单地返回一个 true/false 来返回,然后为字符串设置一个 Session 变量.

Then checking the return value is easy (in theory). I could think of returning simply a true/false for return and then setting a Session variable for the strings.

从一个方法返回多个结果的方法是什么?

What is a way to return multiple results from a method?

推荐答案

创建一个 Result 类并将其返回...

Create a Result class and return that instead...

public class Result
{
   public bool Success {get;set;}
   public string AccessToken {get;set;}
   public string ErrorMessage {get;set;}
}


public Result GetFacebookToken()
{
   Result result = new Result();

   try{
      result.AccessToken = "FACEBOOK TOKEN";
      result.Success = true;
   }
   catch(Exception ex){
      result.ErrorMessage = ex.Message;
      result.Success = false;
   }

   return result;
}

然后你可以调用这个代码...

Then you can call this code like...

Result result = GetFacebookToken();

if(result.Success)
{
   //do something with result.AccessToken
}
else
{
   //do something with result.ErrorMessage 
}

这篇关于从方法返回多个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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