我对 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: Delegate 'OtherDel' does not take '0' arguments.
在一本书:Illustrated C# 2008(第 373 页)中提到,int 变量 y 在 del2 定义的范围内。 那为什么会出现这些错误。
最佳答案
两个问题;
- 您没有将任何东西传递到您的
del2()
调用中,但是它 (OtherDel
) 需要一个您不使用的整数 - 你仍然需要提供它,但是(如果你不使用它们,匿名方法会默默地让你不声明参数 - 它们仍然存在,但是 - 你的方法本质上与del2 = delegate(int notUsed) {...}
) - 委托(delegate) (
OtherDel
) 必须返回一个int
- 你的方法没有
范围界定很好。
关于c# - C# 匿名函数中变量的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2890987/