Convert derived class to base class

后端 未结 6 1307
渐次进展
渐次进展 2020-12-01 13:31

I\'m trying to refresh my memory but can\'t find answers with Google.

public class BaseClass
{
    public virtual void DoSomething()
    {
        Trace.Writ         


        
6条回答
  •  独厮守ぢ
    2020-12-01 14:18

    The solutions with new instead of override break the polymorphism. Recently I came to the same problem and implemented it the following way. My solution has the following advantages:

    • virtual and override stays in place;
    • name BaseClass is not used directly in the type cast, so if I introduce an intermediate MiddleClass in the hierarchy between BaseClass and DerivedClass, which also implements DoSomething(); then the MiddleClass's implementation won't be skipped.

    This is the implementation:

    public class BaseClass
    {
        public virtual void DoSomething()
        {
            Trace.Write("base class");
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public override void DoSomething()
        {
            Trace.Write("derived class");
        }
    
        public void BaseDoSomething()
        {
            base.DoSomething();
        }
    }
    

    The usage is:

        DerivedClass dc = new DerivedClass();
    
        dc.DoSomething();
    
        dc.BaseDoSomething();
    

提交回复
热议问题