INotifyPropertyChanged property name - hardcode vs reflection?

前端 未结 16 1606
感动是毒
感动是毒 2020-11-28 05:13

What is the best way to specify a property name when using INotifyPropertyChanged?

Most examples hardcode the property name as an argument on the PropertyChanged E

16条回答
  •  星月不相逢
    2020-11-28 05:36

    I did something like this once as an experiment, from memory it worked OK, and removed the need to hardcode all the property names in strings. Performance could be in issue if your building a high volume server application, on the desktop you'll probably never notice the difference.

    protected void OnPropertyChanged()
    {
        OnPropertyChanged(PropertyName);
    }
    
    protected string PropertyName
    {
        get
        {
            MethodBase mb = new StackFrame(1).GetMethod();
            string name = mb.Name;
            if(mb.Name.IndexOf("get_") > -1)
                name = mb.Name.Replace("get_", "");
    
            if(mb.Name.IndexOf("set_") > -1)
                name = mb.Name.Replace("set_", "");
    
            return name;
        }
    }
    

提交回复
热议问题