考虑以下代码:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var square = new Square(4);
Console.WriteLine(square.Calculate());
}
}
class MathOp
{
protected MathOp(Func<int> calc) { _calc = calc; }
public int Calculate() { return _calc(); }
private Func<int> _calc;
}
class Square : MathOp
{
public Square(int operand)
: base(() => _operand * _operand) // runtime exception
{
_operand = operand;
}
private int _operand;
}
}
(忽略类设计;我实际上并不是在写计算器!此代码仅表示对需要一段时间才能缩小范围的更大问题的最小重现)
我希望它:
- 打印“16”,或者
- 如果在这种情况下不允许关闭成员字段,则抛出编译时错误
相反,我在指示的行处抛出了一个无意义的异常。在 3.0 CLR 上它是一个NullReferenceException;在 Silverlight CLR 上,它是臭名昭著的Operation could destabilize the runtime。
最佳答案
这是一个已修复的编译器错误。该代码从一开始就不应该是合法的,如果我们要允许它,我们至少应该生成有效代码。我的错。很抱歉给您带来不便。
关于C# - 初始化程序中类字段的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2451311/