C # beginner - Callback in the same function

I am sure this is possible (at least in java) and I am starting C #.

So, I have a function that includes a callback (notifies some other method of the completion of some work).

I don’t want to call another function because I am losing a parameter there (and cannot pass parameters in callback functions). How can I do everything in the same function?

What am I doing now:

public static Tween Play(Tween tweenToPlay) 
{
    return tweenToPlay.Play().OnComplete(RewindCallback);

}

private static void RewindCallback() 
{
    // Execute some code after Tween is completed
}

What I really want:

public static Tween Play(Tween tweenToPlay) 
{
    return tweenToPlay.Play().OnComplete(/*Create a function that will execute here*/);
}
+4
source share
3 answers

Do you need an anonymous method?

public static Tween Play(Tween tweenToPlay) 
{
    return tweenToPlay.Play().OnComplete(() => 
    {
        //... your code
    });
}
+12
source

Do you mean the expression lambda, for example?

public static Tween Play(Tween tweenToPlay) 
{
    return tweenToPlay
        .Play()
        .OnComplete(() => {
            //  Do stuff
        });
}
+14
source

/lambdas , - .

.

- .

:

class Temp
{
    public Tween Tween1;

    public void RewindCallback()
    {
        // Execute some code after Tween is completed
    }
}

:

Temp temp;
public Tween Play(Tween tweenToPlay)
{
    temp = new Temp { Tween1 = tweenToPlay };
    return tweenToPlay.Play().OnComplete(temp.RewindCallback);
}
+3
source

Source: https://habr.com/ru/post/1687664/


All Articles