C# - Example to Refactor-proof reference to members

as we have discussed on the previous example that we have introduce the code snippet like this (see here):

 

 

serializationContext.AddProperty(x => x.BirthDate);

 

in this post, we are going to present a way that demonstrate how we can leverage the Lambda expression and effectively achieve refactor-proof references.

 

Our example is more about a very typical use case - the INotifyPropertyChanged impl. Where normally we will create a Invoke Pattern, and to that patter, one parameter is necessary, that is the name of the parameter. 

 

normally , if we give a string for that name, we loose the ability to guard against changes when code is refactored. So, if we allow passing of a static typed LambdaExpression, such as this (this is a base class that will implements the IPropertyChanged)

 

 

  public class ObservableObject : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;

    #region Protected
    protected void InvokePropertyChanged()
    {
      throw new NotImplementedException();
    }
    protected void InovkePropertyChagned(string name)
    {
      throw new NotImplementedException();
    }
    protected void InvokePropertyChanged(Expression<Func<object>> property_)
    {
      System.Diagnostics.Debug.Assert(property_ != null);
      var body = property_.Body;
      var memberAccessExpression = ((MemberExpression)body);
      var memberName = memberAccessExpression.Member.Name;
      Console.WriteLine("InvokePropertyChanged on {0}", memberName);
    }

    #endregion Protectedk
  }

 

So when we define a Concrete Observable class, and when we need to notify the changes, such as this

 

 

public class ObservableConcreteObject : ObservableObject
  {
    private string m_message;

    public string Message
    {
      get { return m_message; }
      set
      {
        m_message = value;
        
        InvokePropertyChanged("Message");
      }
    }
  }
 

 

You can actually change the call to InvokePropertyChanged as this:

 

 

public string Message
    {
      get { return m_message; }
      set
      {
        m_message = value;
        // you can invoke like this;
        InvokePropertyChanged(() => this.Message);
      }
    }

 

So, all this is possbile when we try to pass in a lambda expression.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值