1

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

4

2 回答 2

4

两个问题;

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

范围界定很好。

于 2010-05-23T07:44:21.297 回答
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);
}
于 2010-05-23T07:44:20.880 回答