为什么必须在静态类中定义C#扩展方法? [英] Why must C# extension methods be defined in static classes?

查看:177
本文介绍了为什么必须在静态类中定义C#扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C#扩展方法必须是静态的.我不明白的是为什么不能在非静态类或泛型类中定义这些扩展?

I understand that C# extension methods must be static. What I don't understand is why these extensions can't be defined in non static classes or generic ones?

更新:我对这个设计决定背后的原因很感兴趣.

Update: I am interested in the reason behind this design decision.

推荐答案

这更多的是观察,而不是答案,但是...

This is more of an observation than an answer, but...

当调用实例方法时,对要调用的对象的引用将作为方法调用中的第一个参数推入堆栈.第一个参数是"this",它是隐式完成的.

When you call an instance method, a reference to the object you are calling is pushed onto the stack as the first argument in your method call. That first argument is "this" and is done implicitly.

定义扩展方法时,将显式定义"this"作为第一个参数.

When you define an extension method, you explicitly define a "this" as the first argument.

如果您可以在同一类中定义扩展方法实例方法,则方法的解析可能会造成混淆,例如,当使用此参数已包含在内.

Is it possible that method resolution would be confusing if you could define extension methods and instance methods in the same class i.e. defining methods with the same name and, in effect, the same parameters when the "this" parameter is included.

这篇关于为什么必须在静态类中定义C#扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆