在运行时实现接口

时间:2013-05-28 22:44:31

标签: c# .net

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

public interface ISomeInterface {
    void SomeMethod();
}

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

这是可能的,如果是,那么如何?

2 个答案:

答案 0 :(得分: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>();

答案 1 :(得分:2)

您可以使用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();