【问题标题】:Scope of variables inside anonymous functions in C#C#中匿名函数内的变量范围
【发布时间】: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


    【解决方案1】:

    两个问题;

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

    范围很好。

    【讨论】:

    • #1 完全正确,但#2:查看 OP 代码顶部的 OtherDel 类型声明:delegate void OtherDel(int x) - 它不返回任何内容。 [编辑:在对问题的编辑中对此进行了更改]
    • 答案反映了我发布此问题时的问题;p
    【解决方案2】:

    错误与作用域无关。您的委托必须返回一个整数值并以一个整数值作为参数:

    del2 = someInt =>
    {
        Console.WriteLine("{0}", y);
        return 17;
    };
    int result = del2(5);
    

    所以您的代码可能如下所示:

    delegate int OtherDel(int x);
    public static void Main()
    {
        int y = 4;
        OtherDel del = x =>
        {
            Console.WriteLine("{0}", x);
            return x;
        };
        int result = del(y);
    }
    

    【讨论】:

      最近更新 更多