Using delegates in C#

前端 未结 5 552
深忆病人
深忆病人 2021-01-30 04:50

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.

5条回答
  •  再見小時候
    2021-01-30 05:35

    The reason is the following:

    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.

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

    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 del = new Func(() => I.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.

    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.

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

    private static Func del = new Func(UserQuery.<.cctor>b__0);
    private static string cctor>b__0()
    {
        return UserQuery.I.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.

提交回复
热议问题