在任何子方法之前(或之后)调用父方法

时间:2019-02-19 15:58:57

标签: c# inheritance

在这里我很可能会得到否定的答案,但我想提我的问题。

C#中是否有一种方法可以在任何子类方法之前(或之后)调用父方法。

public class Base
{
    protected static void ThisWillBeCalledBeforeAnyMethodInChild()
    {
        //do something, e.g. log
    }

    protected static void ThisWillBeCalledAFTERAnyMethodInChild()
    {
        //do something, e.g. log
    }
}

public class SomeClass : Base
{
    public static void SomeMethod1()
    {
        //Do something
    }

    public static void SomeMethod2()
    {
        //Do something
    }
}

因此,我想使用基类中的方法ThisWillBeCalledBeforeAnyMethodInChildSomeMethod1中的SomeMethod2SomeClass之前运行。与after方法类似。

有什么方法可以不通过反射调用方法吗?

3 个答案:

答案 0 :(得分:4)

因此,除了在子方法之前或之后调用base.MethodNameYouWantToCall()之外,您还可以采用其他方法。

这只是一个主意,可能不是您要实现的目标,但是如果我需要在每个子类前后都调用父函数,则可以这样做:

class Parent 
{ 
   protected void Before() { /* does things */ }
   protected void After() { /* does things */ }
   abstract void OtherCode();

   public void PubliclyExposedMethod {
        Before();
        OtherCode();
        After();'
}
class Child : Parent {
      OtherCode { Console.Write("Hello world"); }
}

在上面,您在子级中定义的方法将在before方法之后和after之后进行 ran 。我认为这样做比较干净,因为它减少了您编写base的次数。()

答案 1 :(得分:1)

一个让我大吃一惊的想法是编写一个包装器方法,该方法将一个动作作为参数。在此可以调用之前和之后的方法:

public class SomeClass : Base
{
    public static void SomeMethod1()
    {
        //Do something
    }

    public static void SomeMethod2()
    {
        //Do something
    }

    public static void WrapperMethod(Action action)
    {
        Base.ThisWillBeCalledBeforeAnyMethodInChild();
        action();
        Base.ThisWillBeCalledAFTERAnyMethodInChild
    }

}

您可以这样称呼它:

SomeClass.WrapperMethod(()=> SomeClass.SomeMethod1());

答案 2 :(得分:0)

首先,静态方法不参与继承。

您可以通过使用基本指针来对此进行完全控制,该基本指针是this指针的基类的引用。

class Program
{
    static void Main(string[] args)
    {
        var s = new SOmeClass();

        s.SomeMethod1();
        s.SomeMethod2();
    }
}

public class Base
{
    protected  void ThisWillBeCalledBeforeAnyMethodInChild()
    {
        Console.WriteLine("ThisBefore");
    }

    protected  void ThisWillBeCalledAFTERAnyMethodInChild()
    {
        Console.WriteLine("ThisAFTER");
    }
}

public class SOmeClass : Base
{
    public  void SomeMethod1()
    {
        base.ThisWillBeCalledBeforeAnyMethodInChild();
        Console.WriteLine("SomeMethod1");
    }

    public  void SomeMethod2()
    {
        Console.WriteLine("SomeMethod2");
        base.ThisWillBeCalledAFTERAnyMethodInChild();
    }
}

输出:

此之前 SomeMethod1 SomeMethod2 此后