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

前端 未结 4 1890
鱼传尺愫
鱼传尺愫 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:19

    If you're using .Net 4 you can avoid having to do alot of this as the dynamic type can help with what you want. However if using .Net 2+ there is another (different way) of achieving this:

    You can use a duck typing library like the one from Deft Flux to treat your third party classes as if they implemented an interface.

    For example:

    public interface ICommonInterface
    {
        string Name { get; }
        void DoThirdPartyStuff();
    }
    
    //...in your code:
    ThirdPartyClass1 classWeWishHadInterface = new ThirdPartyClass1()
    ICommonInterface classWrappedAsInterface = DuckTyping.Cast(classWeWishHadInterface);
    
    classWrappedAsInterface.DoThirdPartyStuff();
    

    This avoids having to build derived wrapper classes manually for all those classes - and will work as long as the class has the same members as the interface

提交回复
热议问题