代码之家  ›  专栏  ›  技术社区  ›  Otman IGHOULASSEN

从子类调用基类的扩展方法

  •  0
  • Otman IGHOULASSEN  · 技术社区  · 7 年前

    为什么在子类中,我不能通过直接调用基类来调用为派生类定义的扩展方法(我得到一个编译错误,即基类不包含扩展方法的定义)。 但是,当我直接从子实例调用扩展方法时,我可以在没有任何编译错误的情况下调用它。 下面是我问题的代码:

    using System;
    using System.Reflection;
    
        public class Program
        {
          public static void Main()
          {
             Child child = new Child();
             child.TestMethod();
          }
        }
    
       // Derived class
       public class Mother
       {
    
       }
    
       // Child class
       public class Child : Mother
       {
         public Child() : base()
         {
         }
    
         public void TestMethod()
         {
           this.ExtentionMethod(3);// Ok: no compile errors
           base.ExtentionMethod(3);// Ko: Compilation error (line 27, col 8): 'Mother' does not contain a definition for 'ExtentionMethod'
         }
    }
    
    public static class Extender
    {
       public static void ExtentionMethod(this Mother mother, int i)
       {
         Console.WriteLine($"Mother extention method {i}");
       }
    
    }
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   D Stanley    7 年前

    当您调用扩展方法时,编译器会查看左侧引用的类型,并找到最合适的方法。所以当你打电话的时候 this.ExtentionMethod ,类型 this 用于找到最佳方法。

    因此,在您的情况下,编译器将查找具有 Child 第一个参数。因为没有一个,它会找到一个 Mother 第一个参数(自 小孩 母亲 ).

    使用 base 不执行强制转换-它用于访问基类的成员。由于扩展方法不是“成员”, 基础 不做你期望它做的事。

    另一种选择可能是 铸造 改为基类:

    ((Mother)this).ExtentionMethod(3);
    

    尽管我注意到你没有 不同的 派生类的扩展方法,因此与您发布的内容没有区别 this.ExtensionMethod ((Mother)this).ExtensionBethod . 将调用相同的方法(具有相同的输入值)。

        2
  •  0
  •   Bradley Uffner    7 年前

    这是对 D Stanley's answer .

    如果启用了扩展方法 二者都 Mother Child ,如下所示:

    public static class Extender
    {
        public static void ExtentionMethod(this Mother mother, int i)
        {
            Console.WriteLine($"Mother extention method {i}");
        }
    
        public static void ExtentionMethod(this Child child, int i)
        {
            Console.WriteLine($"Child extention method {i}");
        }
    }
    

    然后,从子类调用它与从基类调用它之间存在区别。

    从内部 小孩

    this.ExtentionMethod(3);
    

    将调用 版本


    ((Mother)this).ExtentionMethod(3);
    

    将调用 版本


    public void TestMethod()
    {
        this.ExtentionMethod(3);
        ((Mother)this).ExtentionMethod(3);
    }
    

    将使用上述两种扩展方法生成以下输出:

    子扩展方法3
    母亲延伸法3

        3
  •  0
  •   nvoigt    7 年前

    其他答案提供了很好的解释 为什么? 如果你有问题,我想确保你知道最快走出困境的方法:

    public void TestMethod()
    {
       this.ExtentionMethod(3); 
       Extender.ExtentionMethod((Mother)this, 3);
    }
    

    this