`

c# - expression tree and lambda - serie 2

    博客分类:
  • C#
c# 
阅读更多

We have covered the topic of expression tree and lambda - serie 1. Serie 2 is like a complementary to serie 1 to cover something that is not the core but may come useful when you are in need of it. 

 

Refactor-Proof references to members

If you are doing some WPF programming you use extensivly the interface called INotifyProeprtyChanged, you may be aware of the refactoirng problem where the properyt name is encoded in the string, which makes the refactoring tools fails to work.

 

The same has been true that if you are doing reflectoin based programing, where if you wan to achieve the function of "use the property of BirthDate defined in my type" you have to use string.

 

With the Expression Tree, you can build a Expression tree representing a property reference using a lambda expression. 

 

The the method can dissect the expresion tree and work ou thte property you mean. 

 

As an example of how it can be used, let's see the following 

 

 

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

 

 

Simpler Reflection

There are some restriction in Generic in C# that generics does not play nicesly with arithmetic operators.

 

The key is to provide a generic Operator class and a nongeneric helper as follow.

 

 

T runningTotal = initialValue; 
foreach (T item i n value) 
{
   runningTotal = Operator.Add(runningTotal, values);
}
 

 

 

TODO:

write some code to go through the use cases. 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics