在每次调用中重用幸存的局部变量。乌布?

Reusing of survived local variable in each call. UB?

我是 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 不会在两次调用之间归零。是"undefined behaviour"吗?看起来它的发生是因为当 result 的范围关闭时,它的生命周期是未定义的。

但是在 C# 中重用活动实体的规则是什么?是规则 - "to reuse always",还是在某些情况下,将创建新的而不是重复使用幸存的旧的?

Is it "undefined behavior"?

不,这是定义明确的行为 - 只是不是您期望的行为。

Looks like it happens because of when scope of result is closed, its life time is undefined.

不,result 的生命周期超出了 m() 的范围。来自 C# 5 规范第 7.15.5.1 节:

When an outer variable is referenced by an anonymous function, the outer variable is said to have been captured by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated (§5.1.7). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.