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

后端 未结 30 2559
梦毁少年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:00

    Create an interface IFooable, then make your A and B classes to implement a common method, which in turn calls the corresponding method you want:

    interface IFooable
    {
        public void Foo();
    }
    
    class A : IFooable
    {
        //other methods ...
    
        public void Foo()
        {
            this.Hop();
        }
    }
    
    class B : IFooable
    {
        //other methods ...
    
        public void Foo()
        {
            this.Skip();
        }
    }
    
    class ProcessingClass
    {
        public void Foo(object o)
        {
            if (o == null)
                throw new NullRefferenceException("Null reference", "o");
    
            IFooable f = o as IFooable;
            if (f != null)
            {
                f.Foo();
            }
            else
            {
                throw new ArgumentException("Unexpected type: " + o.GetType());
            }
        }
    }
    

    Note, that it's better to use as instead first checking with is and then casting, as that way you make 2 casts, so it's more expensive.

提交回复
热议问题