How do Linq Expressions determine equality?

后端 未结 3 885
长情又很酷
长情又很酷 2021-01-11 16:25

I am considering using a Linq Expression as a key in a dictionary. However, I am concerned that I will get strange results, because I don\'t know how Equality is determined

3条回答
  •  伪装坚强ぢ
    2021-01-11 17:21

    As others have noted, Expression's == operator uses the default "reference equality" check - "Are they both a reference to the same place in the heap?". This means that code like your example will likely return false, since your expression literals will be instantiated as different Expression instances regardless of any semantic equality. There are similar frustrations with using lambdas as event handlers:

    MyEvent += (s, a) => DoSomething();
    ...
    MyEvent -= (s, a) => DoSomething(); //<-- will NOT remove the added handler
    

    Checking for semantic equality is tricky. In this particular case, you might be able to visit all the nodes of the expression tree and compare all strings, value types and method references to determine that they do the same thing. However, by inspection, the two lambdas in the following example are semantically equivalent, but you'd have a hard time writing a method to prove it:

       public void MyMethod() {...}
       public void AnotherMethod { MyMethod(); };
    
       ...
    
       Action one = () => MyMethod();
       Action two = () => AnotherMethod();
    
       var equal = one == two; // false
    

提交回复
热议问题