【问题标题】:Implementing an Interface at Runtime在运行时实现接口
【发布时间】:2013-05-29 07:30:42
【问题描述】:

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

public interface ISomeInterface {
    void SomeMethod();
}

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

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

【问题讨论】:

  • 没有。你为什么要这样做?
  • 您不能让 MyClass 实现 ISomeInterface,但您可以生成一个派生自 MyClass 的类并使用 Reflection.Emit 或其他一些技术实现 ISomeInterface。
  • 您可以使用@ThomasLevesque 建议的技术,但如果您给我们您的用例,可能有更好的方法来实现您想要的效果
  • @TyCobb:你为什么暗示没有充分的理由这样做?尽管 C# 不支持这种类型的多态性,但这是一个很好且有效的想法。例如,Haskell 或 Clojure 协议 (IIRC) 中的类型类就是这样工作的。
  • @stakx 我并不是要暗示这一点。我真的很想知道为什么要这样做而不是实现接口。

标签: c# .net


【解决方案1】:

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

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

【讨论】:

  • 哦,太好了...我不知道那个库,但我会记住它以防万一。
  • 真的很棒,这可能是最接近正确性的答案,但我会给这个问题一些时间,看看是否有更好的方法。编辑:这看起来真的很有希望,因为项目描述似乎是针对我正在寻找的确切领域。
【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2014-07-09
    • 2016-05-31
    • 2017-06-22
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多