我只是想知道扩展方法是如何连接到原始类的。我知道在 IL 代码中它调用了静态方法,但它是如何调用的以及为什么它不破坏封装。
最佳答案
他们不“ Hook ”。
Visaul Studio IDE 只是通过在 intellisense 列表中显示它们来让它看起来像它。
编译器“知道”如何处理引用,以便使用正确的参数进行正确的方法调用。
这就是syntactic sugar - 这些方法只是单独静态类上的静态方法。使用 this
修饰符让编译器“知道”添加 ExtensionAttribute
到类以将其标记为扩展方法。
由于扩展方法实际上不更改类并且只能访问其上的公共(public)成员,因此保留了封装。
来自 MSDN :
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
(强调我的)
关于c# - 扩展方法如何连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4478918/