我希望能夠做的幾類如下:泛型類型和繼承
var obj1 = new MyClass { Id = 1 };
var obj2 = new MyClass { Id = 2 };
obj1.Compare(obj2);
我做了如下的擴展方法(inspired by a different question inhere):
public static class ObjExt
{
public static ICollection<string> Compare<T>(this T obj1, T obj2)
{
var properties = typeof(T).GetProperties();
var changes = new List<string>();
foreach (var pi in properties)
{
var value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null);
var value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);
if (value1 != value2 && (value1 == null || !value1.Equals(value2)))
{
changes.Add(string.Format("Value of {0} changed from <{1}> to <{2}>.", pi.Name, value1, value2));
}
}
return changes;
}
現在,這個工程如果我在所有想要比較的課程中都製作了一個方法,所以我想我會把它移到一個超級課堂去幹。
public class MyClass
{
public int Id { get; set; }
public ICollection<string> CompareMe<T>(T obj2)
{
return Compare<T>(obj2);
}
}
如果我將它移動到一個超類,我得到這個編譯錯誤:
Cannot convert instance type argument 'SuperClass' to 'T'
如果我這樣做,我的超類:
return this.Compare<T>(obj2);
我得到一個編譯錯誤說:
The type arguments for method 'Compare(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
如何使這個生成器ic在超級課堂?
也許我不明白,但如果你想將你的方法移到你的超類中,爲什麼你需要一個擴展方法? –
好問題!還有更好的解決方案。重構時我沒有想到這一點。謝謝! –
我可以將評論升級爲答案以將其解決? –