创建一个Observable <T>类:重载=运算符?

hyp*_*man 7 c# wpf overloading observable

我正在尝试创建一个包含值的类,每当值发生更改时都会引发一个事件,并将隐式转换为它所拥有的类型.

我的目标是我应该能够创建一个类的Observable属性,并让另一个类(包括WPF控件)能够读取和写入它,就像它是一个常规字符串一样.其他类可以将它作为Observable维护,或者甚至将其作为自己的属性公开,而不必创建新事件.

这是我到目前为止:

using System;
using System.ComponentModel;

namespace SATS.Utilities
{
    public class Observable<T>
    {
        private T mValue;

        public event EventHandler ValueChanged;
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyValueChanged()
        {
            if (ValueChanged != null)
            {
                ValueChanged(this, new EventArgs());
            }
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            }
        }

        public T Value
        {
            get
            {
                return mValue;
            }
            set
            {
                SetValueSilently(value);
                NotifyValueChanged();
            }
        }

        public void SetValueSilently(T value)
        {
            mValue = value;
        }

        public static implicit operator T(Observable<T> observable)
        {
            return observable.Value;
        }

        public static T operator =(Observable<T> observable, T value) // Doesn't compile!
        {
            observable.Value = value;
            return value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是"="运算符抱怨它不能超载.我想这是有道理的,因为它可能导致各种奇怪的行为.还有另一种方法来实现我的目标吗?

编辑:这是我决定实现这一点的方式.如果有更好的建议请告诉我:)

我意识到这个案例应该由持有Observable的属性来处理.这是我想做的一个例子:

public class A
{
    private readonly Observable<string> _property;

    public Observable<string> Property
    {
        get { return _property; }
    }

    public string Property
    {
        set { _property.Value = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,这不会编译因为Property被定义了两次.这是一种有点hackish的解决方法,我正在考虑以另一种方式定义隐式转换(正如你们许多人所建议的那样):

public static implicit operator Observable<T>(T value)
{
    var result = new Observable<T>();
    result.SetValueSilently(value);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

并使用它来调用属性的setter:

public Observable<string> Property
{
    get { return _property; }
    set { _property.Value = value.Value; }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*aft 4

您可以重载该implicit运算符。

public static operator implicit string(YourObject object)
Run Code Online (Sandbox Code Playgroud)

并走另一条路

public static operator implicit YourObject(string s)
Run Code Online (Sandbox Code Playgroud)

但请注意,这是非常危险的。它可以导致该类的消费者做一些你从未想过的事情;以及一些没有意义的行为。