【发布时间】:2024-04-12 00:20:04
【问题描述】:
我对 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 是命名空间 Practice 中的一个类]
1.error CS1643:并非所有代码路径都以“Practice.Practice.OtherDel”类型的匿名方法返回值 2.error CS1593:委托'OtherDel'不接受'0'参数。
在一本书中提到:Illustrated C# 2008(Page 373) int 变量 y 在 del2 定义的范围内。 那么为什么会出现这些错误。
【问题讨论】:
标签: c# scope anonymous-methods