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.
本文介绍了如何通过Lambda表达式在INotifyPropertyChanged接口中实现refactor-proof引用,避免代码重构时可能引入的问题。通过实例演示了如何在ObservableConcreteObject类中使用Lambda表达式替代传统字符串参数,确保代码的健壮性和可维护性。
5914

被折叠的 条评论
为什么被折叠?



