在静态上下文中调用c#扩展方法有效吗?

在静态上下文中调用c#扩展方法有效吗?,c#,extension-methods,coded-ui-tests,C#,Extension Methods,Coded Ui Tests,我正在开发编码用户界面,正在使用扩展方法,发现了一些有趣的东西。我有一个扩展方法 public static bool Click (this UITestElement Element) {//Code to Click Element and log any errors to framework logger} 我后来不假思索地调用了另一种方法 UITestElement Element = new UITestElement(); //Code to located element C

我正在开发编码用户界面,正在使用扩展方法,发现了一些有趣的东西。我有一个扩展方法

public static bool Click (this UITestElement Element)
{//Code to Click Element and log any errors to framework logger}
我后来不假思索地调用了另一种方法

UITestElement Element = new UITestElement();
//Code to located element
Click(Element);

编译器也没有抱怨。我只是好奇,这个用法有效吗,还是会出现运行时错误

这就是扩展方法在后台的工作方式,在编译时,它们的实例调用转换为静态方法调用

不会有任何运行时错误

见:

在代码中,使用实例方法调用扩展方法 语法但是,由 编译器将代码转换为对静态方法的调用。


扩展方法只不过是静态类中的静态方法,当第一个参数以
this
作为前缀时,这些方法在编译时绑定到实例方法调用。您仍然可以像对待任何其他类一样,将它们视为静态类上的静态方法。因此,这将起作用

举个例子。鉴于此代码:

void Main()
{
    int i = 0;
    i.Foo();
}

public static class IntExtensions
{
    public static int Foo(this int i)
    {
        return i;
    }
}
编译器将发出以下IL(优化已关闭):

如您所见,调用该方法(IL_0004)的实际指令向实际静态类上的静态方法发出
调用。使用哪种语言编写扩展方法并不重要。
IL_0000:  nop         
IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     // i
IL_0003:  ldloc.0     // i
IL_0004:  call        IntExtensions.Foo
IL_0009:  pop         
IL_000A:  ret