我是C#中的新成员。我遇到过这样的代码,例如:在每次调用中重新使用存活的局部变量。 UB?
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
@Evk,我已经改名为问题。由于'result'不是'static',它对我来说看起来很奇怪(在C++之后) - 在每次调用中重复使用相同的变量(使用它的当前值)。 – user1234567