Returning multiple results from a method(从方法返回多个结果)
问题描述
我尝试使用 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
}
这篇关于从方法返回多个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从方法返回多个结果
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
