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

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

    As Pablo suggests, interface approach is almost always the right thing to do to handle this. To really utilize switch, another alternative is to have a custom enum denoting your type in your classes.

    enum ObjectType { A, B, Default }
    
    interface IIdentifiable
    {
        ObjectType Type { get; };
    }
    class A : IIdentifiable
    {
        public ObjectType Type { get { return ObjectType.A; } }
    }
    
    class B : IIdentifiable
    {
        public ObjectType Type { get { return ObjectType.B; } }
    }
    
    void Foo(IIdentifiable o)
    {
        switch (o.Type)
        {
            case ObjectType.A:
            case ObjectType.B:
            //......
        }
    }
    

    This is kind of implemented in BCL too. One example is MemberInfo.MemberTypes, another is GetTypeCode for primitive types, like:

    void Foo(object o)
    {
        switch (Type.GetTypeCode(o.GetType())) // for IConvertible, just o.GetTypeCode()
        {
            case TypeCode.Int16:
            case TypeCode.Int32:
            //etc ......
        }
    }
    

提交回复
热议问题