Why we use “this” in Extension Methods?

后端 未结 6 1260
遥遥无期
遥遥无期 2021-01-17 10:36

I want to ask why we use \"this\" keyword before the parameter in an extension method (C# Language)........... like this function :

    public static int ToI         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 10:54

    For info, the significance of this as a contextual-keyword here is largely that it avoids introducing a new keyword. Whenever you introduce a new keyword you risk breaking code that would have used it as a variable / type name. this has a few useful features:

    • it is close enough to indicating that this relates to an instance method
    • it is an existing keyword...
    • ...that would have been illegal when used in that location

    This means that no existing code will be broken.

    Beyond the choice of this as the keyword, it is just a convenient syntax for the compiler, and more convenient than adding [Extension] manually. Without either, it would just be a static method, without any special behaviour.

提交回复
热议问题