首页 > 解决方案 > 如何返回只有一个字段的命名元组

问题描述

我在 C# 中编写了一个函数,它最初返回一个命名元组。但是现在,我只需要这个元组的一个字段,我想保留这个名称,因为它有助于我理解我的代码。

private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() {
        // do something
        return (true, false);
    }

这个函数编译。但这是我想要的以下功能

private static (bool informationAboutTheExecution) doSomething() {
        // do something
        return (true);
    }

错误信息:

元组必须至少包含两个元素

不能将类型 'bool' 隐式转换为 '(informationAboutTheExecution,?)

有人有解决方案来保留返回值的名称吗?

标签: c#

解决方案


我只想添加另一个选项,尽管他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);
    }
}

推荐阅读