我的客户提出了一个奇怪的要求,即对于项目代码中的每个 .ToString() 调用,我们都应该进行自定义操作(例如在 db 中添加一行)
我觉得扩展方法对我很有用,如果它为我提供了压倒一切的设施。
为什么微软不允许扩展方法覆盖类方法的现有行为?
我听说编译器将扩展方法的优先级低于类方法。有没有办法将编译器修改为优先于扩展方法而不是类方法?
最佳答案
Is there a way to modify compiler to priorities extension methods more than class methods?
不,你不能。
我会从类似的 question 中引用 Eric Lippert :
The purpose of extension methods is to extend the set of methods available on a type, not to override existing methods; that's why they're called "extension methods"
来自 MSDN - Extension Method :
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.
关于c# - 扩展方法编译器优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14869563/