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

后端 未结 4 1316
不思量自难忘°
不思量自难忘° 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:44

    You cannot do that. You should probably design your class hierarchy differently, because it looks strange that C inherits from B, while behaving like A.

    Anyway, it could make sense in your case. Then you should make another method in A which you will not override:

    class A {
        protected virtual void basicM() {}
        public virtual void M() { basicM(); }
    }
    class C {
        public override void M() { basicM(); }
    }
    

    BTW, if you name the method as I did in the example, then you should probably rethink the whole thing. If this hierarchy is justified, than basicM probably performs something that deserves to be a separate method with a different name, perhaps even a public method.

提交回复
热议问题