2

是否可以让已经编译的类在运行时实现某个接口,例如:

public interface ISomeInterface {
    void SomeMethod();
}

public class MyClass {
    // this is the class which i want to implement ISomeInterface at runtime
}

这可能吗,如果是,那怎么办?

4

2 回答 2

5

差不多吧。您可以使用即兴界面。

https://github.com/ekonbenefits/impromptu-interface

来自https://github.com/ekonbenefits/impromptu-interface/wiki/UsageBasic的基本示例:

using ImpromptuInterface;

public interface ISimpleClassProps
{
  string Prop1 { get;  }
  long Prop2 { get; }
  Guid Prop3 { get; }
}

var tAnon = new {Prop1 = "Test", Prop2 = 42L, Prop3 = Guid.NewGuid()};
var tActsLike = tAnon.ActLike<ISimpleClassProps>();
于 2013-05-28T22:48:41.590 回答
3

您可以使用该Adapter模式使其看起来像是您实现了接口。这看起来有点像这样:

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();
    }
}

使用它看起来有点像这样:

Myclass baseobj = new Myclass();
ISomeInterface obj = new SomeInterfaceAdapter(baseobj);
obj.SomeMethod();
于 2013-05-28T22:58:46.627 回答