【问题标题】:Extension method and Regular Method => Error?扩展方法和常规方法 => 错误?
【发布时间】:2010-10-22 23:29:41
【问题描述】:

我有两种相同的方法。 一个是

    public void ExtendFrameIntoClientArea(Window w, int amount)
    {
        if (internals.DwmIsCompositionEnabled())
        {
            WindowInteropHelper wi = new WindowInteropHelper(w);
            internals.DwmExtendFrameIntoClientArea(wi.Handle, new internals.MARGINS(amount));
        }
    }

另一个是

public void ExtendFrameIntoClientArea(this Window w,int amount)
        {
            this.ExtendFrameIntoClientArea(w, amount);
        }

其中一个是扩展方法,另一个不是。但是,这会导致错误“此调用不明确”

我将如何解决这个问题?

【问题讨论】:

  • 它可以编译吗?扩展方法必须是静态的...

标签: c# c#-4.0 extension-methods


【解决方案1】:

扩展方法应该是静态的。

public static class XExtender
{
    public static void A(this X x)
    {
        x.A(x);
    }
}
public class X
{
    public void A(X x)
    {

    }
}

扩展方法应该有一个静态类和一个静态方法。

【讨论】:

  • 我相信这只是一个错字 - 如果没有 static 修饰符将无法编译。
  • 我只是想知道:如果扩展方法与类型中定义的方法具有相同的签名:bit.ly/91A9Jn(一般指南),那么它的意义何在?
【解决方案2】:

根据C# Version 3.0 Specificationsearch order 是:

  • 类型定义中的实例方法
  • 当前命名空间中的扩展方法
  • 当前命名空间的父命名空间中的扩展方法
  • “using”导入的其他命名空间中的扩展方法

那么你是如何声明你的方法的以及在哪里声明的?

【讨论】:

    【解决方案3】:

    我认为错误不是扩展方法引起的。

    一、扩展方法

    public static void ExtendFrameIntoClientArea(this Window w, int amount) { }
    

    (顺便说一句,您错过了static 修饰符)与实例方法会模棱两可

    public void ExtendFrameIntoClientArea(int amount) { }
    

    Window 类中声明,但不使用实例方法

    public void ExtendFrameIntoClientArea(Window w, int amount) { }
    

    无论在哪个类中声明。此外 - 据我所知 - 实例方法优先于扩展方法 - 所以它们永远不应该与扩展方法模棱两可。我建议再次查看错误消息并确认您正在查看正确的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 2012-04-09
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      相关资源
      最近更新 更多