开发者

Suggestions for abstracting lambda expressions

I find myself using lambda expressions more and more in my C# applications. The most common case is using Expression<Func<Object>> to eliminate magic-string references to property names. For instance, I can have a method such as:

public void SomeFunction(Expression<Func<Object>> expression)
{ ... }

I can call 开发者_如何学Gothe method as:

SomeFunction(() => SomeProperty);

The logic inside the method that handles the expression is almost identical in every implementation so far which has me considering a way to extract this into a reusable component. Has anyone done this? Any potential pitfalls I should be aware of?


Well, yes and no. The big difference there is the inference used to populate a dictionary. (I agree with most of the responses to that post and don't like its use in that case.) Here, I am merely using the expression to pass in a reference to a property rather than passing in a magic-string containing the property name.

And, my initial implementation actually came directly from a Microsoft blog! In that case, and one of the instances where I'm using this, is in my RaisePropertyChanged method. Using the expression, I can call:

RaisePropertyChanged(() => MyProperty);

instead of:

RaisePropertyChanged("MyProperty").

IMHO, this makes the code more reliable and maintainable as I get type checking/validation at compile time so I'll know immediately if someone has changed the name or removed a property from the calling object.

My issue is that I'm using this same approach in a few other places as well and find that I am duplicating the logic used to handle the expression. I'd considered creating a new class that derived from Expression<Func<Object>> and use that as the type whenever I want this behavior, but I know there's a lot under-the-hood with expressions, lambda's et al so I would like some confidence that I won't be opening Pandora's Box doing this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜