【问题标题】:c# Call child method from parent methodc#从父方法调用子方法
【发布时间】:2020-05-21 08:45:10
【问题描述】:
public class ClassParrent
{    
        public void Page_Load(object sender, EventArgs e)
        {
            if (CurrentActionKey == ActionKeys.Enum.create)
                    Page_Load_create(sender,e);
            if (CurrentActionKey == ActionKeys.Enum.update)
                    Page_Load_update(sender, e);
        }    
        public virtual void Page_Load_create(object sender, EventArgs e){}
        public virtual void Page_Load_update(object sender, EventArgs e){}
}

public class ClassChild : ClassParrent
{
        public override void Page_Load_create(object sender, EventArgs e){}
        public override void Page_Load_update(object sender, EventArgs e){}
}

有什么方法可以在 ClassParrent 调用 Page_Load 时调用 ClassChild 中的 override 方法?

测试来自Call child method from parent c# 的答案,但不起作用。

【问题讨论】:

  • 您可以为函数指定“abstract”关键字,但只有在您不打算在 ClassParrent 中为这些函数编写代码时才有效。
  • 附加问题有什么问题?
  • 我不使用'abstract',因为它有很多子类,而且大多数类不需要抽象方法的实现
  • @Pavel Anikhouski : 不行,调用了虚拟方法
  • 实际上在子类中是网络表单

标签: c# asp.net oop


【解决方案1】:
public class ClassParrent
{    
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (CurrentActionKey == ActionKeys.Enum.create)
                    Page_Load_create(e);
            if (CurrentActionKey == ActionKeys.Enum.update)
                    Page_Load_update( e);
        }    
        public virtual void Page_Load_create(EventArgs e){}
        public virtual void Page_Load_update(EventArgs e){}
}

public class ClassChild : ClassParrent
{
        public override void Page_Load_create(EventArgs e){}
        public override void Page_Load_update(EventArgs e){}
}

修复它:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2012-01-21
    • 2016-02-14
    相关资源
    最近更新 更多