c# - C# 匿名函数中变量的作用域

标签 c# scope anonymous-methods

我对 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 定义的范围内。 那为什么会出现这些错误。

最佳答案

两个问题;

  1. 您没有将任何东西传递到您的 del2() 调用中,但是它 (OtherDel) 需要一个您不使用的整数 - 你仍然需要提供它,但是(如果你不使用它们,匿名方法会默默地让你不声明参数 - 它们仍然存在,但是 - 你的方法本质上del2 = delegate(int notUsed) {...})
  2. 委托(delegate) (OtherDel) 必须返回一个 int - 你的方法没有

范围界定很好。

关于c# - C# 匿名函数中变量的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2890987/

相关文章:

c# - 如何在没有文本框的情况下获取键盘事件?

c# - 为什么 SubSonic 的 ActiveRecord T4 模板生成 ActiveRecord1.cs 而不是 ActiveRecord.cs?

c# - 如何为多个 BO 属性定义 IDataErrorInfo 错误属性

C# 函数 : access local variables in a block

javascript - 获取点击元素的索引

C#:是否可以在匿名方法中声明局部变量?

c# - Predicate<int>匹配题

c# - 自定义属性的构造函数何时运行?

javascript - 尝试添加多个 D3 图

c# - 通过匿名方法分配匿名类型的属性