简体   繁体   中英

Blazor generic component with eventcallback

I created a Component to which the parent component can bind to. Here is a minified example:

<input @bind=@Value />
@code {
    [Parameter]
    public EventCallback<string> ValueChanged { get; set; }
    [Parameter]
    public string Value
    {
        get => _Value;
        set
        {
            if (_Value == value) return;
            _Value = value;
            ValueChanged.InvokeAsync(value);
        }
    }
}

It is working and the parent component can bind to the value and gets the updates.

I want to make the component generic now. That means, that I want the parent component to be able to also bind an int value. I tried using typeparam, but then this line

if (_Value == value) return;

was not working anymore.

How do I make this component generic?

You can't compare generic types directly using == , you need to have a method of comparing.

The correct way to do this is explained by his highness @JonSkeet here by using EqualityComparer<T>.Default.Equals(x, y);

So your comparison code (assuming the generic type is TItem ) is:


[Parameter] public EventCallback<TItem> ValueChanged { get; set; }

[Parameter] public TItem Value
   {
      get => _Value;
      set
         {
            if (EqualityComparer<T>.Default.Equals(_Value, value)) return;
            _Value = value;
            ValueChanged.InvokeAsync(value);
         }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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