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

ang*_*mbr 6 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
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我想ThisWillBeCalledBeforeAnyMethodInChild从Base类中的方法在之前SomeMethod1SomeMethod2之中运行SomeClass.与after方法类似.

没有用反射调用方法有没有办法做到这一点?

mat*_*net 0

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

您可以通过使用基指针来完全控制 this,基指针是对 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

ThisBefore SomeMethod1 SomeMethod2 ThisAFTER