How to invoke (non virtually) the original implementation of a virtual method?

后端 未结 4 1324
不思量自难忘°
不思量自难忘° 2020-12-18 01:14

I have the following situation:

In a 3rd party library (can not be modified):

class A { public virtual void M() {} }

class B : A { public override v         


        
4条回答
  •  不知归路
    2020-12-18 01:49

    I’m afraid this is not possible directly the way you describe — the purpose of virtual methods is for the overriding to be transparent. So the only way to do this at all is via a workaround.

    Let me try to whip one up, but please be aware that this is a hacky suggestion. If you really need this construct in your code, it may be an indication that your code has a fundamental design flaw somewhere else, so restructuring something might be more desirable than filling it with yet another design flaw. But anyway, here goes...

    class A {
        public virtual void M() { m_protected(); }
        protected void m_protected() { /* code goes here */ }
    }
    
    class B {
        public override void M() { /* code here, possibly invoking base.M() */ }
    }
    
    class C {
        public override void M() { m_protected(); }
    }
    

提交回复
热议问题