提问人:Pierre-olivier Gendraud 提问时间:4/8/2021 最后编辑:Pierre-olivier Gendraud 更新时间:4/9/2021 访问量:2025
如何返回只有一个字段的命名元组
How to return a named tuple with only one field
问:
我在 c# 中编写了一个函数,它最初返回一个命名元组。 但是现在,我只需要这个元组的一个字段,我想保留这个名字,因为它可以帮助我理解我的代码。
private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() {
// do something
return (true, false);
}
此函数编译。但这是我想要的以下功能
private static (bool informationAboutTheExecution) doSomething() {
// do something
return (true);
}
错误消息:
元组必须包含至少两个元素
不能隐含地将类型“bool”转换为“(informationAboutTheExecution,?)
有人有没有解决方案来保留返回值的名称?
答:
9赞
Marc Gravell
4/8/2021
#1
基本上,你不能。您可以返回 ,但它没有名称。您不能手动添加,因为编译器明确不允许添加 (CS8138)。你可以回去.您可以执行以下操作,但它并不比返回更有用:ValueTuple<bool>
[return:TupleElementNamesAttribute]
bool
bool
private static ValueTuple<bool> doSomething()
=> new ValueTuple<bool>(true);
部分问题在于,在引入值元组语法之前,它已经是一个有效的表达式,这就是为什么({some expression})
private static ValueTuple<bool> doSomething()
=> (true);
是不允许的。
6赞
Nailuj29
4/8/2021
#2
如果您必须为您的申报表命名,您可以这样做:
private static void doSomething(out bool information) {
// do something
information = true;
}
然后用
bool result;
doSomething(out result);
评论
2赞
Marc Gravell
4/8/2021
或者只是 ?bool doSomething()
1赞
Sweeper
4/8/2021
@MarcGravell这不是“命名你的回报”,是吗?
1赞
Tim Schmelter
4/8/2021
@MarcGravell:这是 OP 的问题,他想要这个布尔值的名称,但方法名称是不够的,因为它没有描述布尔值,而是描述了方法的作用。该参数是完美的解决方法。out
9赞
Tim Schmelter
4/8/2021
#3
我只想添加另一个选项,尽管他是最简单的解决方法,但 Marc 已经解释了为什么这是不可能的。我只需为它创建一个类:out
public class ExecutionResult
{
public bool InformationAboutTheExecution { get; set; }
}
private static ExecutionResult DoSomething()
{
// do something
return new ExecutionResult{ InformationAboutTheExecution = true };
}
该类可以轻松扩展,还可以确保它永远不会为 null,并且可以使用如下所示的工厂方法创建,例如:
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);
}
}
评论
2赞
Jeroen Mostert
4/8/2021
这是我们过去在元组根本不存在时所做的,就可扩展性而言,它仍然很难被击败(与元组不同,添加字段不会破坏现有的调用者)。
0赞
Jeroen Mostert
4/8/2021
顺便说一句,像这样非常简单的类(通常是不可变的)也是在可用的情况下实现为主要候选类(即.这为您提供了一些好处,例如免费比较。record
record ExecutionResult(bool InformationAboutTheExecution) { public static ExecutionResult Success { get; } = new(true); }
评论
out
DoSomethingResult