Using string constant for notify property changed

前端 未结 4 1359
-上瘾入骨i
-上瘾入骨i 2021-01-15 13:49

I am working with some existing code and trying to figure out the advantage (if any) of using a string constant for the name of a property when implementing INotifyPropertyC

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 14:20

    To answer your question (trying to figure out the advantage) : there is an advantage for an observer who know your type and wait for a specific property to change

    void Observe(Customer c)
    {
        c.PropertyChanged += (s, e) => 
        {
            if (e.PropertyName == Customer.CustomerIdPropertyName)
            {
                MessageBox.Show("New id " + Customer.CustomerId);
            }
        }
    }
    

    If you want to go futher :

    Typing errors can be avoided using a property selector expression to fill your CustomerIdPropertyName.

    You won't need it with nameof keyword (CTP). If you don't have this kind of observer, CalleMemberNameAttribute is the easiest way.

提交回复
热议问题