在静态上下文中调用 C# 扩展方法是否有效?

Is it valid to call c# extension methods in a static context?

我正在研究编码 UI 并尝试使用扩展方法并发现了一些有趣的东西。我有一个扩展方法

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);

并且编译器没有抱怨。我只是好奇,这种用法是否有效,还是会出现运行时错误?

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

不会有任何运行时错误。

参见:Extension Methods (C# Programming Guide)

In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method.

扩展方法无非就是staticclasses内部的静态方法,当第一个参数以this为前缀时,在编译时绑定到实例方法调用。您仍然可以像其他方法一样将它们视为静态 class 上的静态方法。因此,这将起作用。

一个例子。鉴于此代码:

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

public static class IntExtensions
{
    public static int Foo(this int i)
    {
        return i;
    }
}

编译器将发出以下 IL(优化已关闭):

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     

如您所见,调用方法 (IL_0004) 的实际指令向实际静态 class.

上的静态方法发出 call