c# - 如何返回只有一个字段的命名元组
问题描述
我在 C# 中编写了一个函数,它最初返回一个命名元组。但是现在,我只需要这个元组的一个字段,我想保留这个名称,因为它有助于我理解我的代码。
private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() {
// do something
return (true, false);
}
这个函数编译。但这是我想要的以下功能
private static (bool informationAboutTheExecution) doSomething() {
// do something
return (true);
}
错误信息:
元组必须至少包含两个元素
不能将类型 'bool' 隐式转换为 '(informationAboutTheExecution,?)
有人有解决方案来保留返回值的名称吗?
解决方案
我只想添加另一个选项,尽管他out
是最简单的解决方法,Marc 已经解释了为什么它不可能。我会简单地为它创建一个类:
public class ExecutionResult
{
public bool InformationAboutTheExecution { get; set; }
}
private static ExecutionResult DoSomething()
{
// do something
return new ExecutionResult{ InformationAboutTheExecution = true };
}
该类可以轻松扩展,您还可以确保它永远不会为空,并且可以使用以下工厂方法创建,例如:
public class SuccessfulExecution: ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult{ InformationAboutTheExecution = true };
}
public class FailedExecution : ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult { InformationAboutTheExecution = false };
}
现在您可以编写如下代码:
private static ExecutionResult DoSomething()
{
// do something
return SuccessfulExecution.Create();
}
如果出现错误(例如),您可以添加一个ErrorMesage
属性:
private static ExecutionResult DoSomething()
{
try
{
// do something
return SuccessfulExecution.Create();
}
catch(Exception ex)
{
// build your error-message here and log it also
return FailedExecution.Create(errorMessage);
}
}
推荐阅读
- angular - 在 Ionic 4 的选项卡内路由
- kubernetes - 用于出站流量的 Knative/Kubernetes 唯一 IP
- java - 替换字符串中的 $ 符号
- python-3.x - 如何使用 python 对树莓派进行编程以输入模拟值
- c++ - 如何专门化模板类的成员结构
- c - 如何解决c中的冲突类型错误?
- java - Jenkins Android Build failed , gradlew build env: sh: No such file or directory
- html - 编码新手,需要帮助修复 html/css 线框
- android - 如何确定用户之前是否使用 google firebase 登录
- python - Pandas Concat 添加空单元格/列