如果变量与参数不同,下面的函数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
......
}
}