C# code to handle different classes with same method names

前端 未结 9 1532
夕颜
夕颜 2020-12-10 01:56

Let\'s say you have two different C# classes A and B that while not deriving from the same base class do share some of the same names for methods.

相关标签:
9条回答
  • 2020-12-10 02:52

    You can use an interface to accomplish what you want to do.

    interface IConnectable
    {
        void Connect();
    
        void Disconnect();
    }
    

    Both A and B should implement IConnectable. Then use IConnectable instead of Object as the parameter type for your method and you should be all set.

    public void MakeConnection(IConnectable connectable)
    {
        connectable.Connect();
    
        // Do some more stuff...
    
        connectable.Disconnect();
    }
    

    Edit: Since you don't have the source code, you have a couple of options:

    1. Use Max's solution of using the dynamic keyword, (if you are using .NET 4.0)
    2. Use Steve's solution of using casting and if/else statements
    3. Create wrapper classes for A and B and have them implement the interface (or use common abstract base class for them)

    For example:

    class AWrapper : IConnectable
    {
        private A obj;
    
        public AWrapper(A obj)
        {
            this.obj = obj;
        }
    
        public void Connect()
        {
            this.obj.Connect();
        }
    
        public void Disconnect()
        {
            this.obj.Disconnect();
        }
    
        // other methods as necessary
    }
    

    (BWrapper would be similar, just using B instead of A)

    Then you could create the wrappers and pass them into MakeConnection. It's up to you how you want to do it. Depending on your situation, one method may be easier than the others.

    0 讨论(0)
  • 2020-12-10 02:54

    If the interface solution is not possible (e.g you don't have source code), another less effecient solution is to use reflection.

    0 讨论(0)
  • 2020-12-10 02:57

    As others have said, re-factoring to use interfaces or using the dynamic approach are probably the most elegant ways.

    If this is not possible you could cast the object to your types. I'd suggest using as and then checking that the cast worked, an unchecked cast would be dangerous if someone called this with a type that failed to cast.

    E.g. If types A and B both have a method called DoSomething() then this will work...

        public static void CallDoSomething(object o)
        {
            A aObject = o as A;
    
            if (aObject != null)
            {
                aObject.DoSomething();
                return;
            }
    
            B bObject = o as B;
    
            if (bObject != null)
            {
                bObject.DoSomething();
                return;
            }
        }
    

    BUT this is pretty ugly to be honest... I'd really try and refactor to interfaces.

    0 讨论(0)
提交回复
热议问题