在C#中使用委托 [英] Using delegates in C#

查看:160
本文介绍了在C#中使用委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,我也有新的C#语言和.NET框架。你能不能帮我理解的代表? 我试图检查一些code,发现我得到的结果是意想不到的我。在这里,它是:

I'm new here and I'm also new in C# language and .NET framework. Could you help me with understanding delegates? I was trying to check some code, and found that the results I received were unexpected for me. Here it is:

class Program
{
    public static int I = 0;

    static Func<string> del = new Func<string>(I.ToString);

    static void Main(string[] args)
    {
        I = 10;
        Console.WriteLine("{0}", del());
    }
}

答案是0,而不是10。为什么? 谢谢你,我很抱歉我的英文不好。

The answer was 0, but not 10. Why? Thank you and I'm sorry about my poor English.

推荐答案

究其原因如下:

您声明它直接指向了的ToString 静态INT实例的方法,委托的方式。它被捕获在创建时

The way you declare the delegate it points directly to the ToString method of the static int instance. It is captured at the time of creation.

由于flindeberg指出,在下面的意见,每位代表都有一个目标和方法,在目标执行。

As flindeberg points out in the comments below, each delegate has a target and a method to be executed on the target.

在这种情况下,要执行的方法是明显的的ToString 方法。有趣的部分是方法上执行的实例:这是在创建时的情况下,这意味着该委托没有使用来获得使用实例,但它存储的参考实例本身。

In this case, the method to be executed is obviously the ToString method. The interesting part is the instance the method is executed on: It is the instance of I at the time of the creation, meaning that the delegate is not using I to get the instance to use but it stores the reference to the instance itself.

之后,您更改为不同的值,基本分配给它一个新的实例。这并不神奇地改变你的委托拍摄的情况下,又何必呢?

Later you change I to a different value, basically assigning it a new instance. This doesn't magically change the instance captured in your delegate, why should it?

要获得预期的结果,你需要委托改成这样:

To get the result you expect, you would need to change the delegate to this:

static Func<string> del = new Func<string>(() => I.ToString());

这样的,委托指向一个一个执行匿名方法的ToString 上的电流在时间委托的​​执行。

Like this, the delegate points to an anonymous method that executes ToString on the current I at the time of the execution of the delegate.

在这种情况下,要执行的方法是在将委托中声明的类创建匿名方法的实例为null,因为它是一个静态方法

In this case, the method to be executed is an anonymous method created in the class in which the delegate is declared in. The instance is null as it is a static method.

看一看在code编译器生成的委托的第二个版本:

Have a look at the code the compiler generates for the second version of the delegate:

private static Func<string> del = new Func<string>(UserQuery.<.cctor>b__0);
private static string cctor>b__0()
{
    return UserQuery.I.ToString();
}

正如你所看到的,这是做的的东西的常规方法。在我们的情况下,它会返回调用的ToString 对当前实例的结果

As you can see, it is a normal method that does something. In our case it returns the result of calling ToString on the current instance of I.

这篇关于在C#中使用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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