gpt4 book ai didi

c# - 基类中的运行方法和子类中的附加运行方法

转载 作者:行者123 更新时间:2023-11-30 20:55:40 25 4
gpt4 key购买 nike

我希望能够在我的基类 displaySomething() 中运行该方法另外在我的子类中运行名为 displaysomething() 的方法

这可能吗?请问我怎样才能做到这一点?

我有一个看起来像这样的基类

public class baseClass
{
public void displaySomething()
{
MessageBox.Show("Method from base class: display something");
}
}

我有一个看起来像这样的子类

public class subClass : baseClass
{

public void displaySomething()
{
MessageBox.Show("Additional method to run after base class method");
}

}

我有一个看起来像这样的按钮点击事件。

private void button1_Click(object sender, EventArgs e)
{
subClass mySubClass = new subClass();
mySubClass.displaySomething();
}

最佳答案

需要在子类重写方法的实现中加入对基类重写方法的调用,像这样:

public void displaySomething() {
// You can decide to call the base before, after,
// or in the middle of your new method.
base.displaySomething();
MessageBox.Show("Additional method to run after running base class method");
}

请注意,您的代码不会覆盖该方法,因为它未声明为 virtual。您需要这样声明:

public class baseClass {
public virtual void displaySomething() ...
}
public class subClass : baseClass {
public override void displaySomething() ...
}

关于c# - 基类中的运行方法和子类中的附加运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18178119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com