显式接口实现的扩展方法绑定

Extension method binding for explicit interface implementation

我一直在研究扩展方法,以便为现有界面添加一些功能。当我隐式实现接口成员时,编译器选择接口成员实现而不是扩展方法,如 this MSDN 页面中所述。

但是,当我尝试显式实现时,似乎选择了扩展方法而不是接口的实现成员。

//My interface and extension method for this interface
interface IExt
{
    void Extended(int e);
}

public static int Extended(this yapboz.IExt ext, int e)
{
    return e + 1;
}

当我显式实现给定的扩展方法(下面的 CExt)时,它没有绑定。

class CExt : IExt
{
    void IExt.Extended(int e)
    {
        throw new NotImplementedException();
    }
}

在这个实现之后它 returns 整数值而不是抛出异常!

但是,当我隐式实现接口成员时(见下文),我的代码会抛出异常。

class CExt : IExt
{
    public void Extended(int e)
    {
        throw new NotImplementedException();
    }
}

必须通过接口调用显式实现。所以

IExt c = new CExt();
c.Extended(1);

将绑定到显式接口实现,因为变量是接口类型,但是

CExt c = new CExt();
c.Extended(1);

将绑定到扩展方法,因为 CExt 类型本身没有 public Extended 方法。

所以这就是为什么它的行为如此。但是我会注意到,添加与现有接口方法相同的扩展方法并不是一个好主意。扩展方法用于扩展接口和类,而不是向现有接口方法添加实现。