【发布时间】:2010-03-17 16:18:39
【问题描述】:
我想解决在未来开发中使用扩展方法和放大类接口的问题(现在是假设的,但将来可能是真实的)。
例子:
/* 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" */
我的问题是:有什么方法可以防止这种情况(我没有找到)?如果现在是如何防止它,有没有办法找到这样的可能问题?如果是现在如何找到可能的问题,我应该禁止使用扩展方法吗?
谢谢。
编辑:
你的回答很有用。 我可以找到代码中使用扩展方法的位置吗?和/或我能否找到代码中使用实例方法但存在具有相同签名的扩展方法的位置?
【问题讨论】:
标签: c# .net extension-methods language-features