如何返回只有一个字段的命名元组

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);
    }
}

  • This is what we used to do when tuples were not a thing at all, and in terms of extensibility it's still hard to beat (adding fields will not break existing callers, unlike with tuples).

回答

你不能,基本上。您可以返回 a ValueTuple<bool>,但它没有名称。您不能[return:TupleElementNamesAttribute]手动添加,因为编译器明确不允许您添加 (CS8138)。你可以直接返回bool。您可以执行以下操作,但它并没有比返回更有帮助bool

    private static ValueTuple<bool> doSomething()
        => new ValueTuple<bool>(true);

部分问题是在引入值元组语法之前({some expression})已经是一个有效的表达式,这就是为什么

    private static ValueTuple<bool> doSomething()
        => (true);

不被允许。


回答

如果您必须命名您的退货,您可以这样做:

private static void doSomething(out bool information) {
    // do something
    information = true;
}

然后用

bool result;
doSomething(out result);

  • or just `bool doSomething()` ?

以上是如何返回只有一个字段的命名元组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>