Is there a better alternative than this to 'switch on type'?

后端 未结 30 2844
梦毁少年i
梦毁少年i 2020-11-22 03:28

Seeing as C# can\'t switch on a Type (which I gather wasn\'t added as a special case because is relationships mean that more than one distinct

30条回答
  •  余生分开走
    2020-11-22 04:22

    Another way would be to define an interface IThing and then implement it in both classes here's the snipet:

    public interface IThing
    {
        void Move();
    }
    
    public class ThingA : IThing
    {
        public void Move()
        {
            Hop();
        }
    
        public void Hop(){  
            //Implementation of Hop 
        }
    
    }
    
    public class ThingA : IThing
    {
        public void Move()
        {
            Skip();
        }
    
        public void Skip(){ 
            //Implementation of Skip    
        }
    
    }
    
    public class Foo
    {
        static void Main(String[] args)
        {
    
        }
    
        private void Foo(IThing a)
        {
            a.Move();
        }
    }
    

提交回复
热议问题