c# - 为什么不能直接调用扩展方法?

标签 c# extension-methods

有人可以向我解释为什么在接下来的第三次调用 DoSomething 时无效吗? (错误消息是“名称‘DoSomething’在当前上下文中不存在”)

public class A { }
public class B : A
{
    public void WhyNotDirect()
    {
        var a = new A();
        a.DoSomething();  // OK
        this.DoSomething();  // OK
        DoSomething(); // ?? Why Not
    }
}
public static class A_Ext
{
    public static void DoSomething(this A a)
    {
        Console.WriteLine("OK");
    }
}

最佳答案

可以像调用其他静态 方法一样调用扩展方法。

将其更改为 A_Ext.DoSomething(this)

如果您问为什么不在 this 上隐式调用它,答案是规范就是这样编写的。我认为原因是在没有限定符的情况下调用它会产生误导。

关于c# - 为什么不能直接调用扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3906170/

相关文章:

c# - 有什么方法可以避免 C# 中的属性内联优化?

c# - VS2010扩展性: how to do custom actions on pressing F5

entity-framework - 使用Moq和Autofac在单元测试中 Entity Framework 的扩展方法

f# - 是否可以在 F# 中定义通用扩展方法?

c# - ASP.NET MVC : Why is `ToMvcHtmlString` not public?

c# - List<T> 没有实现 SyncRoot!

c# - 如何在 wp7 的隔离存储中存储整数值?

c# - 将 XML 转换为 JSON 到 C# 对象

c# - 如何返回 C# 扩展中的子类?

.net - 扩展方法和类型约束