Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

wpf - typesafe NotifyPropertyChanged using linq expressions

Form Build your own MVVM I have the following code that lets us have typesafe NotifyOfPropertyChange calls:

public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property)
{
    var lambda = (LambdaExpression)property;
    MemberExpression memberExpression;
    if (lambda.Body is UnaryExpression)
    {
        var unaryExpression = (UnaryExpression)lambda.Body;
        memberExpression = (MemberExpression)unaryExpression.Operand;
    }
    else memberExpression = (MemberExpression)lambda.Body;
    NotifyOfPropertyChange(memberExpression.Member.Name);
 }

How does this approach compare to standard simple strings approach performancewise? Sometimes I have properties that change at a very high frequency. Am I safe to use this typesafe aproach? After some first tests it does seem to make a small difference. How much CPU an memory load does this approach potentially induce?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What does the code that raises this look like? I'm guessing it is something like:

NotifyOfPropertyChange(() => SomeVal);

which is implicitly:

NotifyOfPropertyChange(() => this.SomeVal);

which does a capture of this, and pretty-much means that the expression tree must be constructed (with Expression.Constant) from scratch each time. And then you parse it each time. So the overhead is definitely non-trivial.

Is is too much though? That is a question only you can answer, with profiling and knowledge of your app. It is seen as OK for a lot of MVC usage, but that isn't (generally) calling it in a long-running tight loop. You need to profile against a desired performance target, basically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...