表达式树中的等式不使用正确的运算符重载

时间:2016-09-29 17:07:54

标签: c# expression-trees roslyn

我遇到了表达式树和运算符重载的奇怪问题(尤其是==!=运算符)。

我正在使用Marc Gravell的答案中的MemberwiseComparer,或多或少的答案

public static class MemberComparer
{
    public static bool Equal<T>(T x, T y)
    {
        return EqualComparerCache<T>.Compare(x, y);
    }

    static class EqualComparerCache<T>
    {
        internal static readonly Func<T, T, bool> Compare = (a, b) => true;

        static EqualComparerCache()
        {
            var members = typeof(T).GetTypeInfo().DeclaredProperties.Cast<MemberInfo>()
                .Concat(typeof(T).GetTypeInfo().DeclaredFields.Where(p => !p.IsStatic && p.IsPublic).Cast<MemberInfo>());
            var x = Expression.Parameter(typeof(T), "x");
            var y = Expression.Parameter(typeof(T), "y");

            Expression body = null;
            foreach (var member in members)
            {
                Expression memberEqual;
                if (member is FieldInfo)
                {
                    memberEqual = Expression.Equal(
                        Expression.Field(x, (FieldInfo)member),
                        Expression.Field(y, (FieldInfo)member));
                }
                else if (member is PropertyInfo)
                {
                    memberEqual = Expression.Equal(
                        Expression.Property(x, (PropertyInfo)member),
                        Expression.Property(y, (PropertyInfo)member));
                }
                else
                {
                    throw new NotSupportedException(member.GetType().GetTypeInfo().Name);
                }

                body = body == null ? memberEqual : Expression.AndAlso(body, memberEqual);
            }

            if (body != null)
            {
                var lambda = Expression.Lambda<Func<T, T, bool>>(body, x, y);
                Compare = lambda.Compile();
            }
        }
    }
}

基类ValueObject<T>,用作值对象的基类。

public class ValueObject<T> : IEquatable<T> where T : ValueObject<T>
{
    public virtual bool Equals(T other)
    {
        if (ReferenceEquals(this, other))
            return true;

        return MemberComparer.Equal<T>((T)this, other);
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as T);
    }

    public override int GetHashCode()
    {
        return MemberComparer.GetHashCode((T)this);
    }

    public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
    {
        // If both are null, or both are same instance, return true.
        if (ReferenceEquals(left, right))
        {
            return true;
        }

        // If one is null, but not both, return false.
        if (((object)left == null) || ((object)right == null))
        {
            return false;
        }

        return left.Equals(right);
    }

    public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
    {
        return !(left == right);
    }
}

通常,这适用于实现IEquatable<T>或标量类型和/或字符串的类。但是,当类包含实现ValueObject<T>的类的属性时,比较失败。

public class Test : ValueObject<Test>
{
    public string Value { get; set; }
}

public class Test2 : ValueObject<Test2>
{
    public Test Test { get; set; }
}

TestTest进行比较时效果很好。

var test1 = new Test { Value = "TestValue"; }
var test2 = new Test { Value = "TestValue"; }

Assert.True(test1==test2); // true
Assert.Equals(test1, test2); // true

但是在比较Test2时失败了:

var nestedTest1 = new Test2 { Test = new Test { Value = "TestValue"; } }
var nestedTest2 = new Test2 { Test = new Test { Value = "TestValue"; } }

Assert.True(nestedTest1==nestedTest2 ); // false
Assert.Equals(nestedTest1, nestedTest2 ); // false

// Second Test with referenced Test object
var test = new Test { Value = "TestValue"; }
var nestedTest1 = new Test2 { Test = test }
var nestedTest2 = new Test2 { Test = test }

Assert.True(nestedTest1==nestedTest2 ); // true
Assert.Equals(nestedTest1, nestedTest2 ); // true

==类调用Test2运算符覆盖,但不为Test类调用。当nestedTest1nestedTest2引用相同的Test对象时,它会起作用。因此,在构建和编译表达式时,不会调用==重载。

我找不到它会忽略它的原因。这是对Roslyn的一些改变没有人注意到或表达树生成有什么问题吗?

当然,我可以重写Expression Tree生成来调用.Equals方法,但这会增加更多的复杂性(以及额外的空值检查)。但实际问题是,为什么编译后的表达式树不会使用==重载以及如何使其工作?

2 个答案:

答案 0 :(得分:2)

在挖掘下来之后,问题就出现了。运算符==未在类Test中定义,但在ValueType<T>中定义。

如果你打电话,

// this is used by Expression.Equal (it does not search for base type)

var m = typeof(Test).GetMethod("op_Equality", 
            BindingFlags.Static 
            | BindingFlags.Public | BindingFlags.NonPublic);

//m is null because op_Equality is not declared on "Test"

var m = typeof(ValueObject<>).GetMethod("op_Equality", 
            BindingFlags.Static 
            | BindingFlags.Public | BindingFlags.NonPublic);

// m is not null

这就是Expression不使用运算符相等方法的原因。

似乎Roslyn在编译时确实使用了相等运算符,但是Expression编译器不是Roslyn的一部分,这似乎是行http://referencesource.microsoft.com/#System.Core/Microsoft/Scripting/Ast/BinaryExpression.cs,b3df2869d7601af4中的错误,它不会在基类中搜索方法。

答案 1 :(得分:0)

我最终实现了一个搜索name运算符覆盖方法的方法,并将其作为第4个参数传递给op_Equality

Expression.Equal

在我的简单场景中,使用第一个MethodInfo equalsOperator = FindMethod(memberType, "op_Equality", false); equalityExpression = Expression.Equal( Expression.Property(left, memberInfo), Expression.Property(right, memberInfo), false, equalsOperator); ... private static MethodInfo FindMethod(Type type, string methodName, bool throwIfNotFound = true) { TypeInfo typeInfo = type.GetTypeInfo(); // TODO: Improve to search methods with a specific signature and parameters while (typeInfo != null) { IEnumerable<MethodInfo> methodInfo = typeInfo.GetDeclaredMethods(methodName); if (methodInfo.Any()) return methodInfo.First(); typeInfo = typeInfo.BaseType?.GetTypeInfo(); } if (!throwIfNotFound) return null; throw new InvalidOperationException($"Type '{type.GetTypeInfo().FullName}' has no '{methodName}' method."); } 就足够了op_Equality ValueObject<T>类中应该不超过一个{I},我确保MemberComparer.Equal<T>((T)this, other)只是AMDGPUMCInstLower::lower - Pseudo instruction doesn't have a target-specific version: 317 当两个对象属于同一类型时调用。