Home > Blockchain >  Understanding subscribing to an Action<int>
Understanding subscribing to an Action<int>

Time:11-04

I need help understanding the following.

I declare an Action for when the variable Count changes:

public Action<int>? CountChanged { get; set; }

and then I subscribe to the action as follows:

protected override void OnInitialized()
{
    this.data.CountChanged  = (newCount) => this.StateHasChanged();
}

I do not fully understand the line of code below:

this.data.CountChanged  = (newCount) => this.StateHasChanged();

My best guess is that it means something like 'when Count changes pass the new value of count as a parameter to the delegate' in this case it is unused, it simply calls the StateHasChanged method. If this is the case, What is the = for?

CodePudding user response:

Firstly, an Action is a delegate.

There are many ways to add a method to a delegate. As delegates are "multicast" they can hold more than one assigned method. The = adds the method to the right to the delegate while the -= removes it.

The first one below is the most obvious, assigning an existing method. All the others create anonymous methods that are assigned to the action.

    public Action<int>? CountChanged { get; set; }

    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount  ;
    }

    protected override void OnInitialized()
    {
        this.CountChanged  = OnCounterChanged;
        this.CountChanged  = (int value) => this.StateHasChanged();
        this.CountChanged  = (value) => { this.StateHasChanged(); };
        this.CountChanged  = value => this.StateHasChanged();
        this.CountChanged  = _ => this.StateHasChanged();
    }

    private void OnCounterChanged(int value)
    {
        this.StateHasChanged();
    }
  • Related