开发者

Why this is required for extension methods of super classes?

Here is a sample code showing the oddity: (code fixed based on 开发者_开发技巧comment)

public class C{}
public static class E {
  public static void Foo(this C o) { }
 }
class D:C {
  void test() {
//  Foo(); // will not compile
    this.Foo(); // compile ok
  }
}

naturally in a real scenario class C would be a class i do not have access to its source code

Anyone knows why this odd requirement to use the this keyword?


Looking at the C# spec, section 7.6.5.2 specifies that extension method invocations only apply for method calls of the following formats:

expr . identifier ( )  
expr . identifier ( args )  
expr . identifier < typeargs > ( )  
expr . identifier < typeargs > ( args )  

When it is a standalone method call, there is no expr, so it does not look for an extension method. This follows because without an expr, it doesn't know what the first argument of the extension method should be.


This is not because D is a subclass of C. (Which in your example, btw, it is not.) This is because extension methods are "syntactic sugar" that makes it appear that a method belongs to a class, even when it doesn't. This compiler feature turns any call of callingObject.Foo(); into Foo(callingObject); by the compiler.

In your commented out code, the compiler doesn't know what to use as the first parameter to your extension method (i.e. it doesn't know what you want this C o to be) because no object of type C or a subclass of C is calling it.

If you were to call the extension method from your base class, you would see the same behaviour.

Hope this helps clear up some confusion.


If you have access to change the code of the class... Why would you want to use an extension method? Extension methods are useful for those classes you don't have the ability to change. I would imaging this would be a frowned upon programming practice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜