1

可能重复:
测试 lambda 表达式相等性的最有效方法
如何检查两个 Expression<Func<T, bool>> 是否相同

如何像这个示例一样测试两个表达式是否相同

        string firstname = "Ahmed";
        Expression<Func<string, bool>> exp1 = (s) => s.Contains(firstname);
        Expression<Func<string, bool>> exp2 = (s) => s.Contains(firstname);

        Console.WriteLine(exp1 == exp2);//print false as two references are no equal

现在如何确保 expression1 等于 expression2 ,因为它们具有相同的标准?

4

2 回答 2

4

如果你想检查表达式是否相等,而不仅仅是它们总是以相同的方式计算,你可以这样做:

exp1.ToString() == exp2.ToString()

请注意,即使是微不足道的更改也会导致它返回 false,例如制作它j => j.Contains(firstname)exp2从此类中使用:

public class Test
{
    static string firstname;
    public static Expression<Func<string, bool>> exp2 = s => s.Contains(firstname);
}

(even though the lambdas look the same in the code, the ToStrings show that one is using Test.firstname and the other is using a compiler-generated class's firstname)

Still, this might be useful depending on where your expressions come from.

于 2012-09-01T17:04:54.177 回答
1

这是ExpressionEqualityComparer可以显示如何执行此操作的代码。

https://source.db4o.com/db4o/trunk/db4o.net/Db4objects.Db4o.Linq/Db4objects.Db4o.Linq/Expressions/

于 2012-09-01T16:12:37.163 回答