表达式与nameof [英] Expression vs nameof

查看:163
本文介绍了表达式与nameof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

expressions上使用nameof提取属性名称是个好主意吗?

It is a good idea to use nameof over expressions for extracting property names?

//method with expression
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression, bool isValid, [param: Localizable(true)] string validationError)
{
    string propertyName = PropertySupport.ExtractPropertyName(propertyExpression);
    RaisePropertyChanged(propertyName, isValid, validationError);
}

//the same logic without expression
protected void RaisePropertyChanged(string propertyName, [param: Localizable(true)] string validationError)
{
    RaisePropertyChanged(propertyName, validationError == null, validationError);
}

但是通话方式不同

public string Url
{
    set
    {
        //with nameof
        RaisePropertyChanged(nameof(Url), this.GetValidationError());
        //with expression
        RaisePropertyChanged(() => Url, this.GetValidationError());
    }
}

您知道每种方法的优点和缺点是什么?还是只有执行速度很重要?我的意思是nameof将在编译后替换为const值.

What advantages and disadvantages do you know in each approach? Or only execution speed matters ? I mean nameof will be replaced on const value after compilation.

推荐答案

为什么要使用表达式来做一些在编译时可以做的事情? nameof(Url)是在编译时确定的.花费0毫秒.然后进行评估.当您可以使用nameof时,构建表达式既昂贵又毫无意义.

Why use expressions to do something you can do on compile time? nameof(Url) is determined on compile time. It costs 0 ms. to evaluate that afterwards. Building an expression is costly and pointless when you can use nameof.

因此,最重要的是:除非确实需要,否则不要使用表达式(您已经在表达式内部工作并且必须从那里开始).否则,请使用nameof.

So the bottom line is: don't use expressions unless you really have to (you are already working inside an expression and you have to go from there). Otherwise use nameof.

这篇关于表达式与nameof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆