我对 C# 中匿名函数内的变量范围有疑问。
考虑下面的程序:
delegate void OtherDel(int x);
public static void Main()
{
OtherDel del2;
{
int y = 4;
del2 = delegate
{
Console.WriteLine("{0}", y);//Is y out of scope
};
}
del2();
}
我的 VS2008 IDE 出现以下错误:[Practice is a class inside namespace Practice]
1.error CS1643:并非所有代码路径都以“Practice.Practice.OtherDel”类型的匿名方法返回值 2.error CS1593:委托“OtherDel”不采用“0”参数。
有一本书告诉:Illustrated C# 2008(Page 373) int 变量 y在del2 定义的范围内。那么为什么会出现这些错误。