vendredi 24 avril 2020

Get event Action using Reflection in Blazor

I have following service:

public class Service
{

    private List<Model> _modelList = new List<Model>();

    public List<Model> Modellist
    {
        get { return _modelList ; }
        private set
        {
            _modelList = value;
            NotifyStateChanged();
        }
    }

    public event Action OnChange;
    public void NotifyStateChanged() => OnChange?.Invoke();
}

and normally used like:

protected override void OnInitialized()
{
    _Service.OnChange += StateHasChanged;
}

But i want to make that generic, and get the event using reflection. I tried the following with no luck:

protected override void OnInitialized()
{
    var backingField = Service.GetType().GetField("OnChange", BindingFlags.Instance | BindingFlags.NonPublic);
    var delegateInstance = (Action)backingField.GetValue(Service);
    delegateInstance += StateHasChanged;
}

How do I get this working?

Many Thanks!





Aucun commentaire:

Enregistrer un commentaire