匿名方法是内联定义的吗? [英] Are anonymous methods defined inline?

查看:87
本文介绍了匿名方法是内联定义的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内联定义了匿名方法吗?在下面的示例中,委托对象"d"引用了一个匿名方法,该方法正在访问在Fun方法中定义的"x"变量. "x"的范围应限于Fun方法,但是当我们调用MyFun时,它将调用作为参数传递的委托并递增"x"的值.

Are anonymous methods defined inline ? In the example below, the delegate object "d" is having reference of an anonymous method, which is accessing "x" variable which is defined in the Fun method. The scope of "x" should be limited to Fun method, but when we call MyFun, which invokes the delegate passed as parameter and increments the value of "x".

输出结果为"6",这是怎么发生的?如何在匿名方法中使用"x"的值,或者首先是"x"变量本身的值?

The output comes out to be "6", how does this happen ? How the value of "x", or in first place "x" variable itself was available in the anonymous method ?

public delegate void Del();

public void Fun()
{
    int x = 5;
    Del d = delegate { x++;  };
    MyFun(d);
    Console.WriteLine(x);
}

public static void MyFun(Del d)
{
    d();
}

推荐答案

内联定义了匿名方法吗?

Are anonymous methods defined inline?

我不知道内联"是什么意思.

I don't know what "inline" means.

在下面的示例中,委托对象"d"引用了一个匿名方法,该方法正在访问在Del方法中定义的"x"变量.

In the example below, the delegate object "d" is having reference of an anonymous method, which is accessing "x" variable which is defined in the Del method.

否,在Fun方法中定义了x. Del不是方法,它是委托类型.

No, x is defined in the Fun method. Del is not a method, it's a delegate type.

"x"的范围应限于Fun方法.

The scope of "x" should be limited to Fun method.

正确.回想一下,"x的范围"被定义为程序文本中可以通过其非限定名称查找x的区域".您使用的是正确的术语; Fun的主体是x的范围.请注意,匿名方法在Fun内部,因此x在范围内.

Correct. Recall that "the scope of x" is defined as "the region of program text in which x may be looked up by its unqualified name". You are using the term correctly; the body of Fun is the scope of x. Note that the anonymous method is inside Fun and therefore x is in scope.

当我们调用MyFun时,它将调用作为参数传递的委托,并增加"x"的值.

when we call MyFun, it invokes the delegate passed as parameter and increments the value of "x".

正确.

输出结果为"6".

The output comes out to be "6".

正确.

这是怎么发生的?

how does this happen ?

问题尚不完全清楚.听起来您已经提供了有关此情况的解释:变量x在匿名函数内的作用域内,该函数递增变量,因此变量的值会更改.

The question is not entirely clear. It sounds like you've already provided an explanation for how this happens: the variable x is in scope inside the anonymous function, the function increments the variable, so the value of the variable changes.

如果您的问题是为了使这种情况发生,编译器会生成什么代码?"编译器假装您编写了以下内容:

If your question is "what code does the compiler generate in order to make this happen?" the compiler pretends that you wrote something like:

public delegate void Del();

private class Locals
{
    public int x;
    public void AnonymousMethod() { x++; }
}    

public void Fun()
{
    Locals locals = new Locals();
    locals.x = 5;
    Del d = locals.AnonymousMethod;
    MyFun(d);
    Console.WriteLine(locals.x);
}

public static void MyFun(Del d)
{
    d();
}

这篇关于匿名方法是内联定义的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆