抽象 class 中的嵌套抽象 class 以及如何实现它

Nested abstract class in an abstract class and how to implement it

我有一个抽象 class A 和一个抽象方法,其参数再次是抽象 class B 在同一抽象 class A 中定义。当我扩展这个抽象 class A 作为另一个 class C 的一部分,我如何实现带有嵌套抽象参数的方法 class.

public abstract class A<T, V>
{
    public abstract int GetObject(T t, V v);
    public abstract int GetAnotherObject(B b);
    public abstract class B{}
}

这个 class 由另一个 class C

扩展
public class C: A<ABC, DEF>
{
        public C()
        {

        }
        public override int GetObject(ABC abc, DEF def)
        {
            return 10;
        }

        public override int GetAnotherObject(B b)
        {
            return 15;
        }
}

如何使用某些属性实现 class B 并传入 GetAnotherObject 方法。有人可以帮帮我吗

怎么样

public class C<ABC, DEF> : A<ABC, DEF>
{
    public C()
    {

    }
    public override int GetObject(ABC abc, DEF def)
    {
        return 10;
    }

    public override int GetAnotherObject(B b)
    {
        return 15;
    }
}

只需在 class 后缀加上泛型。

来自 ECMA:

Any class nested inside a generic class declaration or a generic struct declaration (§25.2) is itself a generic class declaration, since type parameters for the containing type shall be supplied to create a constructed type.

因此,如果不为 A 提供类型参数,则无法实现嵌套 B

void Main()
{
    var c = new C();
    var result = c.GetAnotherObject(new BImpl<string, int>());
}

public class BImpl<T, V> : A<T, V>.B
{
    public override int BM()
    {
        return 1;
    }
}

// Or you can supply type arguments right here
//public class BImpl : A<string, int>.B
//{
//  public override int BM()
//  {
//      return 1;
//  }
//}

public abstract class A<T, V>
{
    public abstract int GetObject(T t, V v);
    public abstract int GetAnotherObject(B b);
    public abstract class B
    {
        public abstract int BM();
    }
}

public class C : A<string, int>
{
    public C()
    {

    }

    public override int GetObject(string abc, int def)
    {
        return 10;
    }

    public override int GetAnotherObject(B b)
    {
        return b.BM();
    }
}

你已经很接近了。

public class C<ABC, DEF> : A<ABC, DEF>
{
    public C()
    {

    }
    public override int GetObject(ABC abc, DEF def)
    {
        return 10;
    }

    // since B is a nested class of A, it has no scope outside of A
    // outside of the definition of A, it must always be referred to as A.B
    public override int GetAnotherObject(A<ABC,DEF>.B b)
    {
        return 15;
    }
}

public class D : A<ABC,DEF>.B
{
    // implementation of A.B
}

请记住,C 总是 恰好 A.B。您将永远无法定义 A.B 的实现(我们称它为 D)并让 C 的方法签名引用覆盖中的方法签名。 GetAnotherObject 在 A 中定义为采用 A.B,因此必须实施以接受 any A.B,而不是 [=13= 的某些特定实施].

回复:您对如何在 C

中实现 A.B 的评论

C 中实现 A.B 毫无意义。 C 的方法签名中仍然必须包含 A.B 。但如果你真的必须这样做,出于某种原因。

public class C<ABC, DEF> : A<ABC, DEF> 
{
    // C's implementation of A

    public override int GetAnotherObject(A<ABC,DEF>.B b)
    {
        return 15;
    }

    public class D : A<ABC,DEF>.B
    {
        // implementation of A.B
    }
}

请注意 GetAnotherObject 仍然需要 A.B,而不是 D