Use of “this” keyword in formal parameters for static methods in C#

前端 未结 6 1254
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 09:20

I\'ve come across several instances of C# code like the following:

public static int Foo(this MyClass arg)

I haven\'t been able to find an

6条回答
  •  情深已故
    2020-11-27 09:36

    This is an extension method. See here for an explanation.

    Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

    Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework... .

    it means that you can call

    MyClass myClass = new MyClass();
    int i = myClass.Foo();
    

    rather than

    MyClass myClass = new MyClass();
    int i = Foo(myClass);
    

    This allows the construction of fluent interfaces as stated below.

提交回复
热议问题