How to make 2 incompatible types, but with the same members, interchangeable?

前端 未结 4 1854
鱼传尺愫
鱼传尺愫 2020-12-29 16:35

Yesterday 2 of the guys on our team came to me with an uncommon problem. We are using a third-party component in one of our winforms applications. All the code has already b

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 17:35

    What about some wrappers?

    public class ThirdPartyClass1 {
        public string Name {
            get {
                return "ThirdPartyClass1";
            }
        }
    
        public void DoThirdPartyStuff() {
            Console.WriteLine("ThirdPartyClass1 is doing its thing.");
        }
    }
    
    public interface IThirdPartyClassWrapper {
        public string Name { get; }
        public void DoThirdPartyStuff();
    }
    
    public class ThirdPartyClassWrapper1 : IThirdPartyClassWrapper {
    
        ThirdPartyClass1 _thirdParty;
    
        public string Name {
            get { return _thirdParty.Name; }
        }
    
        public void DoThirdPartyStuff() {
            _thirdParty.DoThirdPartyStuff();
        }
    }
    

    ...and the same for ThirdPartyClass2, then you use the wrapper interface in all your methods.

提交回复
热议问题