【发布时间】:2016-12-28 11:49:15
【问题描述】:
我是 C# 新手。我遇到了这样的代码示例:
namespace App1
{
delegate int Sum(int number);
class TestAnonymusMethod
{
static Sum m()
{
int result = 0; // is not zeroed between calls
Sum del = delegate (int number)
{
for (int i = 0; i <= number; i++)
result += i;
return result;
};
return del;
}
static void Main()
{
Sum del1 = m();
for (int i = 1; i <= 5; i++)
Console.WriteLine("Sum of {0} == {1}", i, del1(i));
Console.ReadKey();
}
}
}
输出是:
Sum of 1 == 1
Sum of 2 == 4
Sum of 3 == 10
Sum of 4 == 20
Sum of 5 == 35
如您所见,局部变量 result 在调用之间未归零。它是“未定义的行为”吗?看起来这是因为当result 的范围关闭时,它的生命周期是未定义的。
但是在 C# 中重用活动实体的规则是什么?这是规则 - “总是重复使用”,还是在某些情况下,会创建新的而不是重复使用幸存的旧的?
【问题讨论】:
-
为什么要归零?你只调用一次“m()”方法,所以它被初始化为 0 一次。
-
@Evk,我重命名了问题。由于
result不是static,它对我来说有点奇怪(在 C++ 之后) - 在每次调用中重用相同的变量(及其当前值)。
标签: c# delegates anonymous-function undefined-behavior