Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c# - How does static extension work for js interop in Blazor?

I have managed to make such peace of code.

Blazor html:

@inject IJSRuntime js
<button @onclick="Delete">Delete</button>

Function Delete():

private async Task Delete()
    {
        var confirmed = await js.Confirm($"Are you sure you want to delete?");
    }

Static extension:

    public static class IJSRuntimeExtensionMethods
    {
        public static async ValueTask<bool> Confirm(this IJSRuntime js, string message)
        {
            return await js.InvokeAsync<bool>("confirm", message);
        }
    }

This code makes javascript confirmation pop up.

My question is how does it work?

Most confusing part is:

var confirmed = await js.Confirm($"Are you sure you want to delete?");

Why we can just write Confirm, but not IJSRuntimeExtensionMethodsInstance.Confirm?

Why we also need in this bit js.?

How is it passed through js.Confirm($"Are you sure you want to delete?") to the static extension or what dot notation is exactly doing here after js?

question from:https://stackoverflow.com/questions/66052378/how-does-static-extension-work-for-js-interop-in-blazor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Extension methods are a language feature, that allows you to extend the behavior of any class or interface. Basically this is just syntactic sugar to simplify the call to a static method and make it look like a call to an instance method.

In the declaration of the extension method note the this before IJSRuntime js. This means the method extends the IJSRuntime type:

public static async ValueTask<bool> Confirm(this IJSRuntime js, string message)

Under the hood the call to

js.Confirm("text");

gets translated to

IJSRuntimeExtensionMethodsInstance.Confirm(js, "text");

and you could also call the method like this!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...