【发布时间】:2017-11-30 08:11:14
【问题描述】:
我想知道编写返回值并将其分配给“父”函数中的变量的本地函数的“正确”或“推荐”方式是什么。 (本地函数的“主机”的实际名称是什么?)
我看到了以下 3 种可能性(也许还有更多):
-
在本地函数中使用一个变量并在最后返回这个
private void Foo() { int sum = Sum(1, 2); int Sum(int a, int b) { int localSum = a + b; return localSum; //I know I could write return a + b; but its just a simple demonstration //imagine something more complex, where you intialize an object and work with it in the "Sum" method and than want to return it } } -
使用“父”函数的变量并设置它并使用 void 函数
private void Foo() { int sum; Sum(1, 2); void Sum(int a, int b) { sum = a + b; } } -
结合以上两者,以便更容易阅读
Sum正在设置 sum 变量,但在本地函数中删除变量声明private void Foo() { int sum = Sum(1, 2); int Sum(int a, int b) { sum = a + b; return sum; } }
【问题讨论】:
-
这是非常基于意见的。不过,我绝对不会接受最后一个 - both 会令人困惑。选择一个或另一个 - 返回或变异。
-
我肯定更喜欢第一个。第二种情况就像使用全局变量来共享状态。如果该功能不再存在 - 如果不深入研究其源代码,您将不知道它实际上有什么效果。