值元组存在,那么为什么要使用“out”参数修饰符呢?

J. *_*ini 4 c# out valuetuple

微软关于参数out修饰符的文档指出了以下内容:

使用参数声明方法out是返回多个值的经典解决方法。考虑类似场景的值元组。

我觉得这是一个非常好的观点。out既然我们有了值元组,还剩下什么用例呢?

asc*_*ixi 7

我立即想到的一个主要用例是Try...返回值和布尔值的方法,以便您可以检查操作是否成功:

// With out parameters:
if(int.TryParse(someString, out int result)){
   // do something with the int
}

// With tuples:
var (success, value) = int.TryParseWithTuples(someString);
if(success){
   // do something with the int
}
Run Code Online (Sandbox Code Playgroud)

使用该out参数,符号更清晰,行数更少(并且不需要您为成功布尔值创建局部变量)。它还允许您执行以下操作:

if(int.TryParse(someString, out int r1)){
   // do something with the int
} else if(int.TryParse(fallbackString, out int r2)){
   // do something with the fallback int
} else {
   throw new InvalidOperationException();
}
Run Code Online (Sandbox Code Playgroud)

对于元组,这看起来像这样:

var (success, value) = int.TryParseWithTuples(someString);
if(success){
   // do something with the int
} else {
   (success, value) = int.TryParseWithTuples(fallbackString);
   if(success){
       // do something with the fallback int
   } else {
       throw new InvalidOperationException();
   }
}
Run Code Online (Sandbox Code Playgroud)