是否有可能找出两个表达式是否相同?
如给出以下四个表达式:
Expression<Func<int, bool>> a = x => false;
Expression<Func<int, bool>> b = x => false;
Expression<Func<int, bool>> c = x => true;
Expression<Func<int, bool>> d = x => x == 5;
那么,至少我们可以看到:
但是我能做些什么来在我的代码中找到它吗?
看了一下msdn库,上面写着
Equals
: Determines whether the specified Object is equal to the current Object
. (Inherited from Object
.)
我猜这意味着至少 Expression 类没有重写 equals 方法成为 Equatable?那你会怎么做呢?还是我在这里要求太多? :p
你可以看看类型 ExpressionEqualityComparer在Linq to db4o 中使用.它实现了 IEqualityComparer 接口(interface),因此可用于通用集合以及独立使用。
它使用类型 ExpressionComparison比较两个表达式是否相等,以及 HashCodeCalculation , 从表达式计算哈希码。
这一切都涉及到访问表达式树,因此如果您重复执行它可能会非常昂贵,但它也非常方便。
代码在 GPL 或 dOCL 下可用。
例如,这是您的测试:
using System;
using System.Linq.Expressions;
using Db4objects.Db4o.Linq.Expressions;
class Test {
static void Main ()
{
Expression<Func<int, bool>> a = x => false;
Expression<Func<int, bool>> b = x => false;
Expression<Func<int, bool>> c = x => true;
Expression<Func<int, bool>> d = x => x == 5;
Func<Expression, Expression, bool> eq =
ExpressionEqualityComparer.Instance.Equals;
Console.WriteLine (eq (a, b));
Console.WriteLine (eq (a, c));
Console.WriteLine (eq (a, d));
}
}
它确实打印出 True、False、False。