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

问题描述 投票:0回答:4

我用 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#
4个回答
9
投票

我只是想添加另一个选项,尽管他

out
是最简单的解决方法,而且马克已经解释了为什么这是不可能的。我会简单地为它创建一个类:

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

9
投票

基本上你不能。您可以返回

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

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

问题的一部分是

({some expression})
在引入值元组语法之前已经是一个有效的表达式,这就是原因

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

不允许。


6
投票

如果您必须填写报税表名称,您可以这样做:

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

然后用

调用它
bool result;
doSomething(out result);

0
投票

这是一个旧线程,但只是想补充我的观点。

如果您总是想返回一个结果/值,那么您可以提供第二个返回参数作为“_”。元组赋值的一部分可以使用下划线排除;这称为丢弃。

参考:https://learn.microsoft.com/en-us/archive/msdn-magazine/2017/august/essential-net-csharp-7-0-tuples-explained

就您而言,您的代码是

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

在调用方法中,假设你总是忽略第二个参数,那么你可以使用像:

(bool xyz, _) = doSomething();

或者如果您想要返回第二个参数

(_, bool xyz) = doSomething();

在此,您甚至不需要更改实际的方法代码。

© www.soinside.com 2019 - 2024. All rights reserved.