可以将接口附加到已定义的类

Mar*_*lov 12 c# interface

情况就是这样.在某些情况下,我发现自己想要一个类,让我们称之为class C具有相同功能的类class A,但是已经interface B实现了它的附加功能.现在我这样做:

class C : A,B
{
   //code that implements interface B, and nothing else
}
Run Code Online (Sandbox Code Playgroud)

如果class A碰巧被密封,问题就会出现.有没有一种方法可以制作class A 工具 interface B而无需定义class C(使用扩展方法或其他东西)

Mar*_*ell 8

基本上:没有.这是"mixins"可以带来的一部分,但C#语言目前还不支持(已经讨论了几次,IIRC).

您将不得不使用当前的方法,或(更常见的)只是一个封装 A而不是继承 的传递装饰器A.

class C : IB
{
    private readonly A a;
    public C(A a) {
        if(a == null) throw new ArgumentNullException("a");
        this.a = a;
    }

    // methods of IB:
    public int Foo() { return a.SomeMethod(); }
    void IB.Bar() { a.SomeOtherMethod(); }
}
Run Code Online (Sandbox Code Playgroud)