Force calling the base method from outside a derived class

前端 未结 7 942
野性不改
野性不改 2020-12-10 18:56

I have two classes:

public class MyBase
{
    public virtual void DoMe()
    {

    }
}

public class MyDerived:MyBase
{
    public override void DoMe()
             


        
7条回答
  •  悲哀的现实
    2020-12-10 19:27

    This question is so old but I don't see the following option:

    You can use the 'new' keyword to specify overlapping methods. Then you would simply cast to the class whose method you wish to call.

        public class MyBase
        {
            public virtual void DoMe()
            {
    
            }
        }
    
        public class MyDerived:MyBase
        {
    //note the use of 'new' and not 'override'
            public new void DoMe()
            {
                throw  new NotImplementedException();
            }
        }
    

    Implementation

    var myDerived = new MyDerived();
    var derivedDoMe = myDerived.DoMe();
    var baseDoMe = ((MyBase)myDerived).DoMe();
    

提交回复
热议问题