【问题标题】:how does the out keyword determine scope for a variable that was not declared before being passed?out 关键字如何确定在传递之前未声明的变量的范围?
【发布时间】:2020-06-07 17:41:42
【问题描述】:

当我调用一个带out参数的函数并且在调用它之前没有声明用作参数的变量时,新变量的范围是什么?

我注意到我可以这样做:

if (functionTakesOut(out int newInteger)) {
  Console.WriteLine(newInteger);
}
Console.WriteLine(newInteger);

并且两个 Console.WriteLine() 调用都将起作用。

【问题讨论】:

  • 这是 C# 7 的特性,您只需在使用它的地方声明 newInteger 变量,而不是声明它,例如上面一行

标签: c# out


【解决方案1】:

在示例中,您使用的范围是local...因为您将其声明为您 通过吧。

本质上是一样的:

int newInteger;
if (functionTakesOut(out newInteger)) 
{
  Console.WriteLine(newInteger);
}
Console.WriteLine(newInteger);

【讨论】:

  • 所以..functionTakeOut 必须为该行返回一个布尔值才能编译......说它确实如此。如果 || 左边的表达式是真的......它永远不会评估右侧。
  • 另一方面,您是否使用了常规的“或” |运算符(而不是短路 || 运算符)..然后它将评估双方。
  • @KlausGütter...@the8thbit 后续问题是关于价值而不是范围。
  • 这将是错误的。 int 的默认值为零。
  • 如果 newInteger 从未被声明...并且您使用: if (newInteger >0 || functionTakesOut(out int newInteger) ...这不会编译。
猜你喜欢
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多