简体   繁体   English

检查是否已设置 EventCallback Blazor

[英]Check if EventCallback has been set Blazor

Is there a way to check if EventCallback has been set to something.有没有办法检查EventCallback是否已设置为某些内容。 I am setting mine outside the component and only want to show certain things inside the component if the EventCallback has been set.我在组件外设置我的,如果EventCallback已设置,我只想在组件内显示某些内容。

You can use the HasDelegate property on the EventCallback parameter.您可以对 EventCallback 参数使用 HasDelegate 属性。 This will return a bool indicating whether the event dispatcher is non null这将返回一个布尔值,指示事件调度程序是否为非空

[Parameter]
public EventCallback DoSomething { get; set; }

private bool IsEventSet => DoSomething.HasDelegate;

EventCallBack is a Struct. EventCallBack 是一个结构体。 I was expecting the same thing, such as a way to check if EventCallBack is not null, but since it is a struct, EventCallback.InvokeAsync() won't raise an error if not set, which defies my C# compiler in my brain.我期待同样的事情,例如一种检查 EventCallBack 是否不为空的方法,但由于它是一个结构,因此 EventCallback.InvokeAsync() 如果未设置,则不会引发错误,这在我的大脑中与我的 C# 编译器相悖。

In this example here, if the error handler is not set to something, the exception is never thrown since a Struct cannot be null.在此示例中,如果错误处理程序未设置为某些内容,则永远不会抛出异常,因为 Struct 不能为 null。 Kind of defies logic to me, but it has nothing to call so an error is not thrown.对我来说有点违背逻辑,但它没有什么可调用的,因此不会引发错误。

[Parameter] public EventCallback<string> OnReset { get; set; }

private void ResetFinished()
{  
    try
    {
        // Notify the client the Reset button was clicked.
        OnReset.InvokeAsync("Reset");
    }
    catch (Exception error)
    {
        // for debugging only
        string err = error.ToString();
    }                
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM