为什么表达式不支持IdentityEquality?

时间:2009-09-22 10:36:42

标签: vb.net lambda

ExpressionType枚举中的

There is no IdentityEqual项。如何用VB.NET运算符构造expreesion树?

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用Expression.Equal,指定要使用的实现?

在C#中:

MethodInfo referenceEquality = typeof(object).GetMethod("ReferenceEquals",
    BindingFlags.Static | BindingFlags.Public);
Expression equality = Expression.Equal(lhs, rhs, true, referenceEquality);

这是一个完整的例子(同样,C# - 但你应该能够轻松地翻译它):

using System;
using System.Reflection;
using System.Linq.Expressions;

class Test
{
    static void Main()
    {
        var lhs = Expression.Parameter(typeof(string), "lhs");
        var rhs = Expression.Parameter(typeof(string), "rhs");        
        MethodInfo referenceEquality = typeof(object).GetMethod
            ("ReferenceEquals", BindingFlags.Static | BindingFlags.Public);
        var equality = Expression.Equal(lhs, rhs, true, referenceEquality);
        var lambda = Expression.Lambda<Func<string, string, bool>>
            (equality, new[] { lhs, rhs });

        var compiled = lambda.Compile();

        string x = "hello";
        string y = x;
        string z = new string(x.ToCharArray());
        Console.WriteLine(compiled(x, y)); // True
        Console.WriteLine(compiled(x, z)); // False
    }
}