比较对象的使用EX pression树的所有属性 [英] Comparing all properties of an object using expression trees

查看:133
本文介绍了比较对象的使用EX pression树的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个使用前pression树动态生成比较型该类型的另一个实例的属性实例的所有属性的方法的简单的生成。这适用于大多数的属性,如 INT 字符串,但失败日期时间?(和presumably其他空值类型)。

I'm trying to write a simple generator that uses an expression tree to dynamically generate a method that compares all properties of an instance of a type to the properties of another instance of that type. This works fine for most properties, like int an string, but fails for DateTime? (and presumably other nullable value types).

的方法:

static Delegate GenerateComparer(Type type)
{
  var left = Expression.Parameter(type, "left");
  var right = Expression.Parameter(type, "right");

  Expression result = null;

  foreach (var p in type.GetProperties())
  {
    var leftProperty = Expression.Property(left, p.Name);
    var rightProperty = Expression.Property(right, p.Name);

    var equals = p.PropertyType.GetMethod("Equals", new[] { p.PropertyType });

    var callEqualsOnLeft = Expression.Call(leftProperty, equals, rightProperty);

    result = result != null ? (Expression)Expression.And(result, callEqualsOnLeft) : (Expression)callEqualsOnLeft;
  }

  var method = Expression.Lambda(result, left, right).Compile();

  return method;

}

在一个的DateTime 属性它失败:

防爆$'System.Nullable`1 [System.DateTime的]不能被用于类型参数'System.Object的'法'布尔等于(System.Object的)'类型的对$ pssion

Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for parameter of type 'System.Object' of method 'Boolean Equals(System.Object)'

好了,所以它找到过载等于的期望对象。那么,为什么不能我通过日期时间?成,因为它转换为对象?如果我看可空< T> ,它的确具有的重载equals(对象o)

OK, so it finds an overload of Equals that expects object. So why can't I pass a DateTime? into that, as it's convertible to object? If I look at Nullable<T>, it indeed has an override of Equals(object o).

PS :我知道这是不是一个合适的发电机又因为它不能处理的值,但我会得到的:)

PS: I realize that this isn't a proper generator yet as it can't deal with null values, but I'll get to that :)

更新:伊拿克里斯的回答做了工作,为这个特殊的问题,但最终我去了一个更简单的方法,我觉得就足够了:只要使用防爆pression.Equal 。我认为,包括99%的情况下,我(不知道是否可以处理覆盖等于不覆盖 == ,但没关系)。

UPDATE: Iraklis' answer did work for this particular problem, but in the end I went for a much simpler approach that I think suffices: just use Expression.Equal. I think that covers 99% of my cases (not sure if it can handle overriding Equals without overriding ==, but that's OK).

推荐答案

也许,如果你检查的类型可空与此code工作:

it might work if you check that the types are nullable with this code:

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)){}  

在code样品是从<一个href="http://social.msdn.microsoft.com/Forums/en-US/clr/thread/806ba860-705a-4076-aaf4-ff25a2725c73/"相对=nofollow>此处
如果他们可以为空,那么你可以调用

The code sample is from here
And if they are Nullable then you can call

Nullable.Equals<T>(T? n1, T? n2);

这篇关于比较对象的使用EX pression树的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆