Why we use “this” in Extension Methods?

后端 未结 6 1323
遥遥无期
遥遥无期 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 11:14

    It simply marks it as an extension method, this is the format they chose to go with to define the method as an extension method, as opposed to a plain static method (which is how it's called internally anyway). This is only for the compiler (and intellisense), under the covers your code compiles the same as if you were just calling the static method directly.

    This definition for a method:

    public static int ToInt(string number) //non extension
    

    Needed to be distinguishable from this:

    public static int ToInt(this string number) //extension
    

    Otherwise you'd have intellisense containing every static method in a static class in included namespaces, very undesirable.

提交回复
热议问题