扩展方法需要“this”才能调用?

时间:2012-06-13 17:53:21

标签: c# generics extension-methods

  

可能重复:
  Why is the 'this' keyword required to call an extension method from within the extended class

我在某个命名空间下的程序集中声明了一个扩展方法,它是一个非常常见的帮助器:

using System;

namespace Common {
    public static class GenericServiceProvider {
        public static T GetService<T>(this IServiceProvider serviceProvider) {
             return (T)serviceProvider.GetService(typeof(T));
        }
    }
}

现在在不同的程序集和命名空间中,我正在尝试从实现IServiceProvider的类访问此扩展方法:

using System;
using Common;

namespace OtherNamespace {
    class Bar: IServiceProvider {
        void Foo() {
            GetService<IMyService>(); // doesn't compile
            this.GetService<IMyService>(); // compiles
        }
    }
}

正如您所看到的,我不能直接调用泛型扩展方法,它甚至不会出现在IntelliSense中。但是,如果我在通话前添加“this”,它可以正常工作。

这是在使用.NET 4的Visual Studio 2010中。

这是正常还是我做错了什么?感谢。

3 个答案:

答案 0 :(得分:3)

  

这是正常还是我做错了什么?感谢。

这很正常。扩展方法必须扩展某些东西。编译器不会搜索扩展方法,除非有“表达式”(在。的左侧)。这是在C#语言规范7.6.5.2中定义的:

7.6.5.2 Extension method invocations

In a method invocation (§7.5.5.1) of one of the forms
expr . identifier ( )
expr . identifier ( args )
expr . identifier < typeargs > ( )
expr . identifier < typeargs > ( args )

基本上, expr 总是需要某些。在这种情况下,this可以工作,编译器可以将其重写为:

C . identifier ( expr ) 

答案 1 :(得分:1)

这是因为您只能对该类型的对象使用扩展方法,并且当您的类继承IServiceProvider时,在这种情况下您必须使用this.。 我希望我理解你的问题,这将使你得到答案,但GetService();因为在任何情况下扩展方法的语法都不正确,所以是不可能的。

答案 2 :(得分:0)

扩展方法用于在objects / Class中使用。在这种情况下,您有一个静态类,它的作用类似于类的唯一实例。

因此,如果您创建扩展方法,则对象的实例将能够使用它。

相关问题