为什么EX pression比树木倒影更安全? [英] Why are expression trees safer than reflection?

查看:151
本文介绍了为什么EX pression比树木倒影更安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在<一个href="http://stackoverflow.com/questions/2051065/check-if-property-has-attribute/2051213#2051213">this答案的最快方法的问题,以确定是否属性包含一个给定的属性,用户达林季米特洛夫假定,前pression树比反思更安全。这是真的,如果是这样,为什么是这样吗?

In this answer to the question of the fastest way to determine if a property contains a given attribute, user Darin Dimitrov posited that expression trees are safer than reflection. Is this true, and if so, why is it true?

推荐答案

当你搜索你的领域,因为(在这个问题),您使用字符串重新presentation ID。一旦它改变了你的思考就会崩溃。

Because when you search for your field (as in that question) you use string representation "Id". Once it is changed your reflection will collapse.

什么达林暗示是静态类型:

What Darin suggests is static typing:

Expression<Func<Program, int>> expression = p => p.Id;

您看到了吗?这很有趣,但不出名的C#4.0编译器功能:自动构建拉姆达EX pression EX pression树,并将其转换为防爆pression&LT; T&GT; 。所以,再后来,你可以遍历并获得的MemberInfo 编号的。但它不是万能的反思,因为你不能用字符串

You see that? This is interesting, but not well-known feature of C# 4.0 compiler: automatically build expression tree from lambda expression and cast it to Expression<T>. So then later you can traverse it and get MemberInfo of Id. But it is not as universal as Reflection because you can't search by string.

这篇关于为什么EX pression比树木倒影更安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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