比较Type.GetProperties()和lambda表达式中的PropertyInfo

Pio*_*fer 11 c# reflection equality

在创建我的测试框架时,我发现了一个奇怪的问题.

我想创建一个静态类,它允许我通过属性比较相同类型的对象,但有可能忽略其中的一些.

我希望有一个简单的流畅的API,所以TestEqualityComparer.Equals(first.Ignore(x=>x.Id).Ignore(y=>y.Name), second);如果给定的对象在除了Id和之外的每个属性上都是相等的,那么调用将返回true Name(它们不会被检查是否相等).

这是我的代码.当然这是一个微不足道的例子(缺少一些明显的方法重载),但我想提取最简单的代码.实际情况有点复杂,所以我真的不想改变方法.

该方法FindProperty几乎是来自AutoMapper库的复制粘贴.

用于流畅API的对象包装器:

public class TestEqualityHelper<T>
{
    public List<PropertyInfo> IgnoredProps = new List<PropertyInfo>();
    public T Value;
}
Run Code Online (Sandbox Code Playgroud)

流利的东西:

public static class FluentExtension
{
    //Extension method to speak fluently. It finds the property mentioned
    // in 'ignore' parameter and adds it to the list.
    public static TestEqualityHelper<T> Ignore<T>(this T value,
         Expression<Func<T, object>> ignore)
    {
        var eh = new TestEqualityHelper<T> { Value = value };

        //Mind the magic here!
        var member = FindProperty(ignore);
        eh.IgnoredProps.Add((PropertyInfo)member);
        return eh;
    }

    //Extract the MemberInfo from the given lambda
    private static MemberInfo FindProperty(LambdaExpression lambdaExpression)
    {
        Expression expressionToCheck = lambdaExpression;

        var done = false;

        while (!done)
        {
            switch (expressionToCheck.NodeType)
            {
                case ExpressionType.Convert:
                    expressionToCheck 
                        = ((UnaryExpression)expressionToCheck).Operand;
                    break;
                case ExpressionType.Lambda:
                    expressionToCheck
                        = ((LambdaExpression)expressionToCheck).Body;
                    break;
                case ExpressionType.MemberAccess:
                    var memberExpression 
                        = (MemberExpression)expressionToCheck;

                    if (memberExpression.Expression.NodeType 
                          != ExpressionType.Parameter &&
                        memberExpression.Expression.NodeType 
                          != ExpressionType.Convert)
                    {
                        throw new Exception("Something went wrong");
                    }

                    return memberExpression.Member;
                default:
                    done = true;
                    break;
            }
        }

        throw new Exception("Something went wrong");
    }
}
Run Code Online (Sandbox Code Playgroud)

实际比较器:

public static class TestEqualityComparer
{
    public static bool MyEquals<T>(TestEqualityHelper<T> a, T b)
    {
        return DoMyEquals(a.Value, b, a.IgnoredProps);
    }

    private static bool DoMyEquals<T>(T a, T b,
        IEnumerable<PropertyInfo> ignoredProperties)
    {
        var t = typeof(T);
        IEnumerable<PropertyInfo> props;

        if (ignoredProperties != null && ignoredProperties.Any())
        {
            //THE PROBLEM IS HERE!
            props =
                t.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                    .Except(ignoredProperties);
        }
        else
        {
            props = 
                t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
        }
        return props.All(f => f.GetValue(a, null).Equals(f.GetValue(b, null)));
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上就是这样.

这里有两个测试片段,第一个工作,第二个失败:

//These are the simple objects we'll compare
public class Base
{
    public decimal Id { get; set; }
    public string Name { get; set; }
}
public class Derived : Base
{    }

[TestMethod]
public void ListUsers()
{
   //TRUE
   var f = new Base { Id = 5, Name = "asdas" };
   var s = new Base { Id = 6, Name = "asdas" };
   Assert.IsTrue(TestEqualityComparer.MyEquals(f.Ignore(x => x.Id), s));

   //FALSE
   var f2 = new Derived { Id = 5, Name = "asdas" };
   var s2 = new Derived { Id = 6, Name = "asdas" };
   Assert.IsTrue(TestEqualityComparer.MyEquals(f2.Ignore(x => x.Id), s2));
}
Run Code Online (Sandbox Code Playgroud)

问题在于Except方法DoMyEquals.

返回的属性FindProperty不等于返回的属性Type.GetProperties.我发现的差异在于PropertyInfo.ReflectedType.

  • 无论我的对象的类型,FindProperty告诉我反映的类型是Base.

  • 通过返回的属性Type.GetProperties有其ReflectedType设置为BaseDerived,这取决于实际对象的类型.

我不知道如何解决它.我可以检查lambda中参数的类型,但是在下一步中我想允许类似的结构Ignore(x=>x.Some.Deep.Property),所以它可能不会这样做.

任何有关如何比较PropertyInfo或如何从lambdas正确检索它们的建议将不胜感激.

pay*_*ayo 5

原因FindProperty是告诉你反映TypeBase是因为这是lambda用于调用的类.

你可能知道这个:)

你可以使用它来代替Type中的GetProperties()

static IEnumerable<PropertyInfo> GetMappedProperties(Type type)
{
  return type
    .GetProperties()
    .Select(p => GetMappedProperty(type, p.Name))
    .Where(p => p != null);
}

static PropertyInfo GetMappedProperty(Type type, string name)
{
  if (type == null)
    return null;

  var prop = type.GetProperty(name);

  if (prop.DeclaringType == type)
    return prop;
  else
    return GetMappedProperty(type.BaseType, name);
}
Run Code Online (Sandbox Code Playgroud)

为了解释为什么lambda实际上直接使用Base方法,并且你看到一个不同的PropertyInfo,可能会更好地解释看IL

考虑以下代码:

static void Foo()
{
  var b = new Base { Id = 4 };
  var d = new Derived { Id = 5 };

  decimal dm = b.Id;
  dm = d.Id;
}
Run Code Online (Sandbox Code Playgroud)

这里是b.Id的IL

IL_002f: callvirt instance valuetype [mscorlib]System.Decimal ConsoleApplication1.Base::get_Id()
Run Code Online (Sandbox Code Playgroud)

和IL为d.Id

IL_0036: callvirt instance valuetype [mscorlib]System.Decimal ConsoleApplication1.Base::get_Id()
Run Code Online (Sandbox Code Playgroud)


小智 5

不知道这是否有帮助,但我注意到两个PropertyInfo实例的MetaDataToken属性值相等,如果两个实例都引用相同的逻辑属性,则无论两者的ReflectedType如何.也就是说,两个PropertyInfo实例的Name,PropertyType,DeclaringType和index参数都是相等的.

  • 这很有意思!根据msdn,"MetadataToken"与`Module`结合使用,可以唯一标识元素.谢谢! (3认同)