且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么"静态"和"这&Q​​UOT;需要扩展方法,以及如何在他们的记忆分配呢?

更新时间:2023-02-17 12:58:47

静态和非静态方法之间的唯一区别是,一个非静态方法接受一个隐含参数 - 这个。扩展方法中,不调用在其上的方法被声明的对象的情况下,因此没有办法通过它们的参考,因此它们必须是静态的。

您不能使用关键字的扩展方法里面,我希望这回答了你的第三个问题。该在参数表中该关键字那里只是为了表明哪种类型此方法扩展。

你怎么看内存分配问题?扩展方法就像任何其他的静态方法,只有调用语法是不同的。

A few questions about Extension Methods:

  1. Why are Extension Methods static?

  2. Why do they need to be declared in a static class?

  3. What does the this keyword indicate in the parameter list of extension method? As it is a static class how does the "this" keyword work in this context?

  4. How does memory allocation happen for these type of methods?

The only difference between a static and a non-static method is that a non-static method receives an implicit parameter - this. Extension methods are not called in the context of the object on which the method is declared, therefore there is no way to pass them the this reference, therefore they must be static.

You cannot use the keyword this inside an extension method, I hope this answers your third question. The this keyword in the parameter list is there just to indicate which type this method extends.

What is your question about memory allocation? An extension method is just like any other static method, only the call syntax is different.