1

我已经创建了这个更新方法

 public void Update(Person updated)
   {
       var oldProperties = GetType().GetProperties();
       var newProperties = updated.GetType().GetProperties();
       for (var i = 0; i < oldProperties.Length; i++)
       {
           var oldval = oldProperties[i].GetValue(this, null);
           var newval = newProperties[i].GetValue(updated, null);
           if (oldval != newval)
               oldProperties[i].SetValue(this, newval, null);
       }
   }

它所做的是比较两个 Person 对象以及是否有任何新值。它更新原始对象。这很好用,但作为一个懒惰的程序员,我希望它更可重用。

我希望它像这样工作。

Person p1 = new Person(){Name = "John"};
Person p2 = new Person(){Name = "Johnny"};

p1.Update(p2);
p1.Name  => "Johnny"

Car c1 = new Car(){Brand = "Peugeot"};
Car c2 = new Car(){Brand = "BMW"};

c1.Update(c2);
c1.Brand => "BMW"

c1.Update(p1); //This should not be possible and result in an error.

我正在考虑使用抽象类来保存方法,然后使用一些泛型,但我不知道如何使其特定于类。

4

3 回答 3

3
   public static void Update(object original, object updated)
   {
       var oldProperties = original.GetType().GetProperties();
       var newProperties = updated.GetType().GetProperties();
       for (var i = 0; i < oldProperties.Length; i++)
       {
           var oldval = oldProperties[i].GetValue(original, null);
           var newval = newProperties[i].GetValue(updated, null);
           if (!Equals(oldval,newval))
               oldProperties[i].SetValue(original, newval, null);
       }
   }

或者如果你想确保相同的类型:

   public static void Update<T>(T original, T updated)
   {
       var properties = typeof(T).GetProperties();
       for (var i = 0; i < properties.Length; i++)
       {
           var oldval = properties[i].GetValue(original, null);
           var newval = properties[i].GetValue(updated, null);
           if (!Equals(oldval,newval))
               properties[i].SetValue(original, newval, null);
       }
   }
于 2012-08-01T10:21:01.527 回答
2

您的代码有一个小缺陷,事实上,如果您不强制这两个对象实际上是完全相同的类型,它们可能不具有相同的属性并且您将面临错误。

像这样的泛型方法应该可以在几乎任何东西上正确运行,只要它是 a class(这就是约束where T: class的用途:如果它不是您要传递的类,则代码将无法编译)。

static void Update<T>(T original, T updated) where T : class
{
    var Properties = typeof(T).GetProperties();
    foreach (PropertyInfo property in Properties)
    {
        var oldval = property.GetValue(original, null);
        var newval = property.GetValue(updated, null);
        if (oldval != newval) property.SetValue(original, newval, null);
    }
}
于 2012-08-01T10:27:17.627 回答
1

试试这个模式:

interface IUpdateable
{
void Update(IUpdateable updated)
}

public void Update<T>(T updated) where T:IUpdateable
{
...
...
}
于 2012-08-01T10:20:30.267 回答