Why are expression trees safer than reflection?

后端 未结 4 1577
感动是毒
感动是毒 2021-02-05 11:55

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 reflect

4条回答
  •  灰色年华
    2021-02-05 12:54

    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> expression = p => p.Id;
    

    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. 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.

提交回复
热议问题