Using string constant for notify property changed

前端 未结 4 1384
-上瘾入骨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条回答
  •  死守一世寂寞
    2021-01-15 14:11

    I imagine it is just to avoid bugs caused by typos and try and make the code a little easier to read. Also if you change the name of the property it means changing the value of the const will then work for all code that is checking if the property has changed. e.g. imagine this code:

    public void Main()
    {
        var obj = new ClassWithNotifier();
        obj.OnPropertyChanged += ObjectPropertyChanged;
        DoSomethingWithObj(obj);
    }
    
    private void ObjectPropertyChanged(string propertyName)
    {
        switch (propertyName) {
            case ClassWithNotifier.CustomerIdPropertyName:
                // If the constant changes this will still work
                break;
            case "SomeOtherPropertyName":
                // If you change the property string that is passed here from 
                // your class ClassWithNotifier then this will now break
                break;
        }
    }
    

    In the example above, regardless of the value of the constant the code will work, and if you want to change the property name at some point then you only need to change the constant value and everything will still work with out having to find everywhere we are checking for the name (obviously if you want to change the name of the constant variable as well then you still need to find those references, but finding references to Public fields is easier than searching through the whole project for magic strings)

提交回复
热议问题