c# - 扩展方法编译器优先级

标签 c# .net

我的客户提出了一个奇怪的要求,即对于项目代码中的每个 .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/

相关文章:

c# - 使用c#在ACCESS DATABASE中搜索记录

.net - 导入 OpenAPI 2.0 Postman 集合,所有 POST 请求正文都显示为 x-www-form-urlencoded,而不是原始 JSON

c# - 在 C# 控制台应用程序中实现的 gRPC 中收到的客户端证书为空

c# - 命名空间 'Transactions' 中不存在类型或命名空间名称 'System'

c# - MvvmCross MvxListView 不刷新项目删除

c# - 缺少方法 'instance class [mscorlib]System.Collections.Generic.IEnumerable` 1

C# 通过 for 循环插入数组值

c# - 使用StopWatch测量出现奇怪问题的FPS

c# - 将字符串数组发布到 .net-core mvc

.net - 如何使虚拟 URL 指向部署在 IIS 上的 asp.net 中的 .aspx 页面? (最好没有 IIS)