lundi 30 août 2021

What generic constraint to use in C# for all basic types like int float string etc?

I am trying to implement an Observer pattern in C#, specifically in Unity. I want to make it such that whenever any flags or values change, I want events to fire. So far I have following:

public interface IObservable<T> : IDisposable where T : object
{
    public void Subscribe(Action<T> callback);
}

public class Observable<T> : IObservable<T> where T : object
{
    private Action<T> onValueChanged;

    private T _value;

    public T Value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
            onValueChanged.Invoke(_value);
        }
    }
    public Observable(T newVal)
    {
        _value = newVal;
    }
    public void Subscribe(Action<T> callback)
    {
        onValueChanged += callback;
    }

    public void UnSubscribe(Action<T> callback)
    {
        onValueChanged -= callback;
    }

    public void Dispose()
    {
    }
}

I want this to work on basic types like floats, strings, int, etc, possibly on custom classes too. But currently I am facing this error:

Constraint cannot be special class 'object'

I understand that every class is ultimately a child of object which is why the error is showing. But if I do change the generic constraint to class, I can't use them on basic data-types because they are not reference types, which doesn't work too.

How do I go about doing that, I can't seem to wrap my head around it! Any leads or hints would be greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire