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

标签 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
    }
}

因此,我想在 SomeClass 中的 SomeMethod1SomeMethod2 之前运行基类中的方法 ThisWillBeCalledBeforeAnyMethodInChild。与after方法类似。

有没有不用反射调用方法的方法呢?

最佳答案

因此,除了在您的子方法之前或之后调用 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 方法之前运行。我认为这更干净,因为它减少了您需要编写 base.() 的次数

关于c# - 在任何子方法之前(或之后)调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54770327/

相关文章:

C# HttpClient 损坏的管道,但 curl 有效

c# - 使用 dataGridView 和 BindingSource 的奇怪问题

c# - Intranet 站点的 ASP.NET Identity + Windows 身份验证

c# - 继承与接口(interface)隔离原则

c# - Linq 查询不返回值

c# - 在 C# 命令行应用程序中包含并执行 EXE

c++ - 如果使用基指针声明,为什么简单析构函数不删除派生对象

java - 如何抛出 InvalidLockCombinationException

C# 使用子级 "base"调用尊重的类特定成员引用

java - 从 Java 8 中的 Function 继承的命名具体接口(interface)