我已经创建了这个更新方法
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/