使用linq表达式的Typesafe NotifyPropertyChanged [英] typesafe NotifyPropertyChanged using linq expressions
问题描述
表格构建您自己的MVVM 我有以下代码,使我们可以进行类型安全的NotifyOfPropertyChange调用:
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);
}
与标准的简单字符串相比,这种方法在性能上有何不同?有时我的属性会以很高的频率变化.我可以安全使用此类型安全的方法吗?经过一些初步测试后,它似乎并没有太大的变化.这种方法可能会导致多少CPU内存负载?
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?
推荐答案
引发此问题的代码是什么样的?我正在猜测,就像这样:
What does the code that raises this look like? I'm guessing it is something like:
NotifyOfPropertyChange(() => SomeVal);
这是隐式的:
NotifyOfPropertyChange(() => this.SomeVal);
捕获this
,并且非常意味着每次都要从头开始构建表达式树 (使用Expression.Constant
).然后您每次都解析它.因此,开销绝对是微不足道的.
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.
但是太多了吗?仅凭您的应用程序配置和知识,这就是您可以回答的问题.对于许多MVC使用来说,这被认为是可以的,但是(通常)在长时间运行的紧密循环中并不称呼它.基本上,您需要针对所需的性能目标进行分析.
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.
这篇关于使用linq表达式的Typesafe NotifyPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!