C# code to handle different classes with same method names

前端 未结 9 1566
夕颜
夕颜 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:35

    There is a OOAD concept of 'Programe to an interface not to an implementation' which let's you avoid the chain of inheritance hierarchies

    1- You can create a interfcae

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

    2- And let your classes implement this interface as shown below.

    class A : IConnection
    {
        #region IConnection Members
    
        public void Connect()
        {
           // your connect method implementation goes here.
        }
    
        public void Disconnect()
        {
            // your disconnect method implementation goes here.
        }
    
        #endregion
    }
    
    
    class B : IConnection
    {
        #region IConnection Members
    
        public void Connect()
        {
             // your connect method implementation goes here.
        }
    
        public void Disconnect()
        {
            // your disconnect method implementation goes here.
        }
    
        #endregion
    }
    

    3- Once you done with the implementation than you can make your function accepting an argument of IConnection as shown below.

    public void makeConnection(IConnection con)
        {
            con.Connect();
            con.Disconnect();
        }
    

    4- And from your client code , you can pass the object of classes which implements IConnect Interface.

提交回复
热议问题