多次修改 C# Out 参数

Modifying C# Out parameter more than once

当您的函数具有 out 参数时,最佳做法是在函数内部创建一个新变量并在函数末尾将 out 参数分配给它吗?或者在开头给 out 参数一些 empty/default 值并在整个函数中修改。

我正在尝试想出一些推理来说明为什么其中一种编码 styles/practices 更好用。

选项 1:仅使用 out 参数。

public bool SomeFunc(out string outStr)
{
   outStr = "";

   if (errorCond)
      return false;

   outStr += "foo";
   outStr += "bar";

   return true;
}

选项 2:使用临时变量。

public bool SomeFunc1(out string outStr)
{
   string tempStr = "";
   outStr = "";      // To prevent 'The out parameter must be set' error on return false line.

   if (errorCond)
      return false;

   tempString += "foo";
   tempString += "bar";

   outStr = tempStr;
   return true;
}

虽然这两个都达到了同样的效果,但哪个更可取呢?它们中的任何一个都有缺点吗?

其实没关系,你只需要在这个方法中赋值变量即可。 但是,最好是 to avoid using output or reference parameters:

Working with members that define out or reference parameters requires that the developer understand pointers, subtle differences between value types and reference types, and initialization differences between out and reference parameters.

对我来说,第二个是开销

在方法的开头分配一个默认值,然后根据需要更改该值。

查看 .net 源代码中的示例,例如 int.TryParse or Enum.TryParse