属性更改时取消订阅/重新订阅事件

本文关键字:新订阅 事件 取消 属性 | 更新日期: 2023-09-27 18:06:52

我经常这样写代码:

MyObject property;
MyObject Property
{
    get { return property; }
    set {
            if (property != null)
                property.Changed -= property_Changed; // unsubscribe from the old value
            property = value;
            property.Changed += property_Changed; // subscribe to the new value
        }
}

我正在寻找一种优雅的方式来自动取消订阅。什么好主意吗?

属性更改时取消订阅/重新订阅事件

这是您尝试实现的想法中最优雅的部分。当然,您有一个逻辑错误,即value在传入时可能为空,因此property.Changed += property_Changed会爆炸。

基本上,如果您分配一个新对象,您希望取消订阅旧元素的事件并附加到新元素的事件。

可能是这样的,如果您真的需要在每个属性更改时取消订阅/订阅:

MyObject Property
{
    get { return property; }
    set {
            //unsubscribe always, if it's not null 
            if(property !=null)
               property.Changed -= property_Changed;
            //assign value 
            property = value;
            //subscribe again, if it's not null
            if (property != null)                            
                property.Changed += property_Changed; 
        }
}

也许使用扩展方法可能是你正在寻找的。

你可以试试这样做。

private MyProperty property;
public MyProperty Property
{
    get { return property; }
    set { property.SubPubValue(value, property_Changed); }
}
private static void property_Changed(object sender, PropertyChangedEventArgs e)
{
    throw new NotImplementedException();
}
public static class Extensions
{
    public static void SubPubValue<T>(this T value, T setValue, PropertyChangedEventHandler property_Changed) where T : MyProperty
    {
        if (setValue != null)
            value.PropertyChanged -= property_Changed;
        value = setValue;
        if (setValue != null)
            value.PropertyChanged += property_Changed;
    }
}