Home > Mobile >  EventCallback - is it a func delegate?
EventCallback - is it a func delegate?

Time:07-20

What does this mean?

 public EventCallback<Trail> OnSelected { get; set; }

Does this mean OnSelected is a delegate (function paramter) that holds input parameter of type Trail and return parameter void?

Why is EventCallback used?

If I have to return a parameter of type string for this delegate how would this declaration look like?

will it look like ?

public EventCallback<Trail, string> OnSelected { get; set; }

CodePudding user response:

To answer your first three questions:

An EventCallback is a readonly struct. It's a wrapper for a delegate that supports async behaviour through EventCallbackWorkItem.

It looks like this (extracted from the AspNetCore source code):

public readonly struct EventCallback<TValue> : IEventCallback
{
    public static readonly EventCallback<TValue> Empty = new EventCallback<TValue>(null, (Action)(() => { }));

    internal readonly MulticastDelegate? Delegate;
    internal readonly IHandleEvent? Receiver;

    public EventCallback(IHandleEvent? receiver, MulticastDelegate? @delegate)
    {
        Receiver = receiver;
        Delegate = @delegate;
    }

    public bool HasDelegate => Delegate != null;

    internal bool RequiresExplicitReceiver 
        => Receiver != null && !object.ReferenceEquals(Receiver, Delegate?.Target);

    public Task InvokeAsync(TValue? arg)
    {
        if (Receiver == null)
            return EventCallbackWorkItem.InvokeAsync<TValue?>(Delegate, arg);

        return Receiver.HandleEventAsync(new EventCallbackWorkItem(Delegate), arg);
    }

    public Task InvokeAsync() => InvokeAsync(default!);

    internal EventCallback AsUntyped()
        => new EventCallback(Receiver ?? Delegate?.Target as IHandleEvent, Delegate);

    object? IEventCallback.UnpackForRenderTree()
        => return RequiresExplicitReceiver ? (object)AsUntyped() : Delegate;
}

You can see the above source code and other related code here - enter image description here

  • Related