在这个特定的情况下,第一个更好.
此代码块将任务包装在任务中.它浪费资源:每个任务都是一个状态机对象.
OnClick=@(async () => await DoSomething())>
然而,实际发生的情况取决于MyButton
.
这是一个演示版本.我已经添加了两个按钮事件处理程序,每个按钮事件处理程序都有关于如何执行的注释.
<button @attributes=this.AdditionalAttributes @onclick=this.OnButtonClickAsync></button>
@code {
[Parameter] public EventCallback<MouseEventArgs> OnClick { get; set; }
[Parameter] public RenderFragment? ChildContent { get; set; }
[Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object>? AdditionalAttributes { get; set; }
private async Task OnButtonClickAsync(MouseEventArgs e)
{
// you are awaiting the delegate in the parent component
// if it yields you'll await it's completion
await this.OnClick.InvokeAsync(e);
// Code here will only execute after the parent delegate has completed, awaits and all
// any exceptions will bubble up to here
}
private void OnButtonClick(MouseEventArgs e)
{
// This is a Fire and Forget call
this.OnClick.InvokeAsync(e);
// code here will execute as soon as the parent delegate yields
// exceptions won't bubble up to here
}
}
更广泛地说,这是个人喜好的问题.
我喜欢干净的标记,所以我这样编写代码.
<button disabled="@buttonCss"></button>
@code {
private bool _isDisabled;
private string buttonCss => _isDisabled ? "btn btn-danger" : "btn btn-success";
}
其他人喜欢简洁的[内联]代码.
<button disabled="@(_isDisabled ? "btn btn-danger": "btn btn-success")"></button>
@code {
private bool _isDisabled;
}