c# - 制作一个特定于类的泛型方法

标签 c# .net generics

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

 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.

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

最佳答案

   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);
       }
   }

关于c# - 制作一个特定于类的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11757157/

相关文章:

c# - & 符号 url 编码问题

c# - 在 IIS6 上使用 Decimal In Route 进行路由

c# - Lambda 表达式和方法调用

c# - 将 List<T> 序列化为 XML,并将 XML 反转为 List<T>

c# - RabbitMQ 基本恢复不起作用

c# - dot.Net 委托(delegate)有多少种方法?

c#-4.0 - 为仅在运行时已知的类型创建已编译的 Expession.Lambda

c# - .NET 泛型 : how to resolve type T in run-time?

oracle - 带有基于行类型的集合的 ANYDATA

c# - 如何在WPF窗口中隐藏关闭按钮?