反映和比较复杂类型的属性值?

时间:2014-10-02 21:59:07

标签: c# reflection

如果变量与参数不同,下面的函数AssignIfDiff可以很好地处理简单类型。但是,复杂类型似乎有问题吗?如何使它在复杂类型上工作?

class C 
{ 
     int A { get; set; } 
     List<AClass> B { get; set; }
     ...... 
}
C _c = new C(....); // To be updated

int v = 1;
AssignIfDiff(v, x => x.A); // Update _c.A if it's different than v. It works well.
var b = new List<AClass>(); .....
AssignIfDiff(b, x => x.B); // ???

void AssignIfDiff<T>(T curr, Expression<Func<C, T>> prev)
{
    var expr = (MemberExpression)prev.Body;
    var prop = (PropertyInfo)expr.Member;
    if (!EqualityComparer<T>.Default.Equals(curr, (T)_c[prop.Name]))
    {
        prop.SetValue(_c, curr, null); // Update the property of _c if diff than curr
          ...... 
    }
}

0 个答案:

没有答案