是否有任何直接的方法来确定派生类是调用基类(非抽象)中的方法还是从创建基类实例的某个地方显式调用?
答案 0 :(得分:3)
最简单的方法是使用反射:
public virtual void MyBaseClassMethod()
{
var currType = this.GetType();
if (currType == typeof(MyBaseClass))
{
// base class instantiated directly.
}
}
答案 1 :(得分:0)
如果您可以更改代码,则可以执行以下操作...
public MyDerivedClass : MyBaseClass
{
public override void MyPublicMethod()
{
MyPrivateMethod(false);
}
}
public MyBaseClass
{
public virtual void MyPublicMethod()
{
MyInternalMethod(true);
}
protected void MyInternalMethod(bool isInternal)
{
// If you're planning to use isInternal to change the logic based
// on whether this code has been invoked in the base or subclass
// you would be infinitely better off overriding that code in the
// subclass. Or better still don't use generalization at all and
// use an injection framework and create several implementations
// of an interface.
}
}