Why are expression trees safer than reflection?

后端 未结 4 1564
感动是毒
感动是毒 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:34

    The question as it is stated is why is expression trees safer then reflection.

    The answer is that they are both using reflection.

    Edit to clarify - MemberInfo.GetCustomAttributes is a reflection call.

    http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.getcustomattributes(VS.71).aspx

    0 讨论(0)
  • 2021-02-05 12:38

    If we are talking about type safety and code breaking when renaming properties for example, the expression tree "advantage" is negated now that we have newer C# features like nameof():

    Expression tree way (was better before nameof()):

    Expression<Func<YourClass, int>> expression = p => p.Id;
    var memberExpression = (MemberExpression)expression.Body;
    var property = ((PropertyInfo)memberExpression.Member);
    

    GetProperty from name (was bad before nameof()):

    var property = typeof(YourClass).GetProperty(nameof(YourClass.Id));
    

    The string input in GetProperty wasn't safe, since it was hardcoded to "Id", and when you renamed the Id property, your code would break at runtime if you didn't remember to replace this string aswell.

    That made expression trees safer, because you used the actual name of the property.

    But now that we have nameof(), the string used is actually the name of the property at compile time, and if you rename the property, and you/your IDE "forgets" to rename it in the above snippet aswell, the code will break at compile time.

    So now the old "bad way" is more concise in my opinion and probably performs minimally better aswell, since you don't need the extra casting.

    0 讨论(0)
  • 2021-02-05 12:49

    From my limited knowledge of .NET the expression tree way seems to do type checking.

    0 讨论(0)
  • 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<Func<Program, int>> 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<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.

    0 讨论(0)
提交回复
热议问题