我想解決這個問題使用擴展方法和未來發展類接口的maginification的(現在假設,但未來propably實)。擴展方法和源代碼前進了兼容性
例子:
/* the code written in 17. March 2010 */
public class MySpecialList : IList<MySpecialClass> {
// ... implementation
}
// ... somewhere elsewhere ...
MySpecialList list = GetMySpecialList(); // returns list of special classes
var reversedList = list.Reverse().ToList(); // .Reverse() is extension method
/* now the "list" is unchanged and "reveresedList" has same items in reversed order */
/* --- in future the interface of MySpecialList will be changed because of reason XYZ*/
/* the code written in some future */
public class MySpecialList : IList<MySpecialClass> {
// ... implementation
public MySpecialList Reverse() {
// reverse order of items in this collection
return this;
}
}
// ... somewhere elsewhere ...
MySpecialList list = GetMySpecialList(); // returns list of special classes
var reversedList = list.Reverse().ToList(); // .Reverse() was extension method but now is instance method and do something else !
/* now the "list" is reversed order of items and "reveresedList" has same items lake in "list" */
我的問題是:有沒有一些方法如何防止這種情況下(我沒找到)?如果現在如何防止它,有沒有辦法找到像這樣的可能的問題?如果現在如何找到可能的問題,我是否應該禁止使用擴展方法?
謝謝。
編輯:
此致答案是有用的。 我可以在代碼中找到擴展方法嗎?和/或我可以找到代碼中的哪些地方使用實例方法,但存在具有相同簽名的擴展方法?
是的,我的意思是完全一樣的情況。 如果我理解正確,最正確的方法是使用擴展方法,如靜態方法,不使用擴展方法? 如何在代碼審查中發現,指定的代碼沒有使用擴展方法? – TcKs 2010-03-17 16:48:53
我不認爲Jared說擴展方法的調用就好像它們是普通的靜態方法是正確的;他只是說這是完全避免你所描述的風險的唯一途徑 - 但這種風險無論如何都不是完全可以避免的。 – 2010-03-17 16:52:23
@JacobM正確。 – JaredPar 2010-03-17 17:04:43