【问题标题】:Is there a way to only add code to a method without overriding it completely in c#?有没有办法只在方法中添加代码而不在 c# 中完全覆盖它?
【发布时间】:2013-09-28 14:20:35
【问题描述】:

有没有办法只将代码添加到子类中的方法而不像 c# 中的“覆盖”+“虚拟”那样完全覆盖它。 我发现自己在重写方法中编写了一些重复的代码。不知道该怎么办

【问题讨论】:

  • 在受保护的基类的辅助方法中重构公共代码。
  • 谢谢,我想出了一个解决方案。结果我没想到。在覆盖方法中,我可以只写 base.MethodName()。然后在之前或之后添加一些代码:)

标签: c# overriding virtual


【解决方案1】:

您可以使用具有不同机制的覆盖和虚拟。例如,

class MyBase
    {
        private int MyVar;
        public virtual void DoStuff(int i , int j)
        {
            MyVar = i + j; //This is your common code which is added in base class

        }
    }


    class OverridClass : MyBase
    {
        private int MyNewCount;
        public override void DoStuff(int i, int j)
        {
            MyNewCount = i + j;
            base.DoStuff(i, j); //This is how you reuse your common code and write the code which is more specific to this method

        }
    }`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    相关资源
    最近更新 更多