Implementing an Interface at Runtime

后端 未结 2 458
野的像风
野的像风 2021-01-15 17:21

Is it possible to make an already compiled class implement a certain interface at run time, an example:

public interface ISomeInterface {
    void SomeMethod         


        
2条回答
  •  执念已碎
    2021-01-15 18:02

    You could use the Adapter pattern to make it appear your implementing the interface. This would look somewhat like this:

    public interface ISomeInterface {
        void SomeMethod();
    }
    
    public class MyClass {
        // this is the class which i want to implement ISomeInterface at runtime
    }
    
    public SomeInterfaceAdapter{
        Myclass _adaptee;
        public SomeInterfaceAdapter(Myclass adaptee){
            _adaptee = adaptee;
        }
        void SomeMethod(){
            // forward calls to adaptee
            _adaptee.SomeOtherMethod();
        }
    }
    

    Using this would look somewhat like this:

    Myclass baseobj = new Myclass();
    ISomeInterface obj = new SomeInterfaceAdapter(baseobj);
    obj.SomeMethod();
    

提交回复
热议问题