Implementing INotifyPropertyChanged - does a better way exist?

前端 未结 30 2727
感情败类
感情败类 2020-11-21 05:23

Microsoft should have implemented something snappy for INotifyPropertyChanged, like in the automatic properties, just specify {get; set; notify;} I

30条回答
  •  自闭症患者
    2020-11-21 05:34

    I really like Marc's solution, but I think it can be slightly improved to avoid using a "magic string" (which doesn't support refactoring). Instead of using the property name as a string, it's easy to make it a lambda expression :

    private string name;
    public string Name
    {
        get { return name; }
        set { SetField(ref name, value, () => Name); }
    }
    

    Just add the following methods to Marc's code, it will do the trick :

    protected virtual void OnPropertyChanged(Expression> selectorExpression)
    {
        if (selectorExpression == null)
            throw new ArgumentNullException("selectorExpression");
        MemberExpression body = selectorExpression.Body as MemberExpression;
        if (body == null)
            throw new ArgumentException("The body must be a member expression");
        OnPropertyChanged(body.Member.Name);
    }
    
    protected bool SetField(ref T field, T value, Expression> selectorExpression)
    {
        if (EqualityComparer.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(selectorExpression);
        return true;
    }
    

    BTW, this was inspired by this blog post updated URL

提交回复
热议问题