0

我写ObservableValue<T>来实现INotifyPropertyChanged值类型作为对 .NET 类的补充ObservableCollection<T>

class ObservableValue<T> : INotifyPropertyChanged {
    private T value;
    private PropertyChangedEventHandler eh;

    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged {
        add { eh += value; }
        remove { eh -= value; }
    }

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

    void OnPropertyChanged() {
        if (eh != null)
            eh(this, new PropertyChangedEventArgs("Value"));
    }
}

但是,要使用此类,必须绑定到ObservableValue<T>.Value而不是仅绑定到ObservableValue<T>. 是否可以编写一些魔术代码以ObservableValue<T>在任何T有效的上下文中使用?

4

1 回答 1

1

No, it is not possible to do it for any context: specifically, it is not possible to make it so that you could pass ObservableValue<T> to methods with ref or out parameters of type T.

However, you can come a little closer by defining an implicit conversion operator from ObservableValue<T> to T, letting the users pass instances of ObservableValue<T> to methods that take T by value, or assign ObservableValue<T> to variables of type T without referencing .Value explicitly:

public static implicit operator T(ObservableValue<T> ot) {
    return ot.Value;
}

Of course once an ObservableValue<T> is used in the context where T is expected, it loses its observable behavior: no events will be triggered, and the original ObservableValue<T> object would not be modified.

于 2013-11-03T11:43:53.447 回答