在运行时实现接口

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

public interface ISomeInterface { void SomeMethod(); } public class MyClass { // this is the class which i want to implement ISomeInterface at runtime } 

这是可能的,如果是,那怎么样?

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

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

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