![](/img/trans.png)
[英]Is it possible to override a Method in a Base Class within the same Class (NOT a Derived Class)?
[英]Run same method in base and derived class
首先在基类中运行该方法然后在派生类中运行相同的方法,我需要做什么? 这是一个好主意吗?
我想在基类中运行常见操作,并在同一方法中在派生类中扩展它。 这是通常的做法吗?
public abstract class MyBase
{
void DoStuff()
{
//some common implementation
}
}
public class MyDerived : MyBase
{
void DoStuff()
{
// DoStuff in the base first
// Then DoStuff in here
}
}
你在谈论类似的事吗?
class base
{
protected virtual void method()
{
// do some stuff in base class, something common for all derived classes
}
}
class derived : base
{
public override void method()
{
base.method(); // call method from base
// do here some more work related to this instance of object
}
}
这不是一个坏主意,当我为所有派生类提供一些通用功能时,我会使用它。
如果要保证运行基类逻辑(而不是依赖派生类是礼貌的),可以这样做:
public void Method()
{
//Stuff that should always happen in base class
OnMethod();
}
protected virtual void OnMethod()
{
//Default base class implementation that derived class can either override or extend
}
使用base.TheMethod()
从派生类中运行基类中的方法。
如果要从基类运行派生类的方法,则必须将基类强制转换为派生类。 这意味着您的班级需要知道谁在推导它,这会破坏封装,应该避免。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.