简体   繁体   中英

Using an object passed as a parameter to a function in an inner anonymous function C#

Just for testing purposes, I've created a class MyData that holds an int property called Id.

public class MyData
{
    public int Id { get; set; }
}

Then, in an Main function of an App Console, I initialize two instances of this class.

MyData myData = new MyData() { Id = 1 },
            myData2 = new MyData() { Id = 2 };

And a new object called Property . It's simple an object holding a value and trigger an event when that value changes.

Property p = new Property("Test",
            "System.String",
            "c");

So I simply create a new Property called Test holding an object of type System.String initialized to "c".

Now, I want to set a binding, for example I want to increment the Id of myDatas when the value of the Property changes.

So I've created this static function:

private static void SetBinding(Property p,
    MyData test)
{
    p.PropertyChanged += ((o, r) => 
    {
        test.Id++;
    });
}

And call it into the Main method:

SetBinding(p, myData);
SetBinding(p, myData2);

Debugging, I saw that the Ids are actually incremented. So it seems to work but... I'm not sure about that. In which way the anonymous function keeps track of the variable to modify? Maybe there is a scenario where this my implementation doesn't work anymore?

The compiler generates an additional class...

[CompilerGenerated]
private sealed class <>c__DisplayClass1_0
{
    public MyData test;

    internal void <SetBinding>b__0(object o, PropertyChangedEventArgs r)
    {
        test.Id++;
    }
}

...and replaces your anonymous function with a similar function of the generated class:

private static void SetBinding(Property p, MyData test)
{
    var a = new <>c__DisplayClass1_0();
    a.test = test;
    p.PropertyChanged += a.<SetBinding>b__0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM