首页 > 解决方案 > 不重新定义类型的隐式运算符重载

问题描述

我需要重载隐式运算符,但我需要修改自己的值,而不是为类型创建新值。

public abstract class AbstractScriptableValue<T>//this generic abstract class
{
    [SerializeField] protected T value;//internal value

    protected T previusValue;//previus internal value, for know if the value changes

    public T Value
    {
        get { return value; }
        set
        {
            this.value = value;

            if (!this.value.Equals(previusValue))//if the value change
            {
                previusValue = this.value;//update
                OnValueChanged();//and very importantan!!! notify for a change
            }
        }
    }

    public Action OnValueChanged;
}


public class ValueInt : AbstractScriptableValue<int>
{
    public static implicit operator ValueInt(int argValueA)
    {
         this.Value = argValueA;//error here, because i need evaluate the previus value for notify if it changes, then i set the value for the property .Value, if in this point i create a new value, then i cant notify if it changes.
         return this;
    }
}

感谢您帮助我搜索允许我通知值更改的解决方案。

标签: c#

解决方案


implicit运算符重载方法是static,因此没有可以访问的实例。相反,创建您的类的新实例,然后访问该属性:

public static implicit operator ValueInt(int argValueA)
{
    var result = new ValueInt(); // or whatever constructor you want to call
    result.Value = argValueA;
    return result;
}

推荐阅读