c# - 抽象类中嵌套抽象类及其实现方式

标签 c# abstract-class inner-classes abstraction

我有一个抽象类 A 和一个带有参数的抽象方法,该参数又是在同一个抽象类 A 中定义的抽象类 B。当我将这个抽象类 A 扩展为另一个类 C 的一部分时,我该如何实现该方法嵌套抽象类的参数。

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

这个类由另一个类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;
        }
}

如何实现具有某些属性的类 B 并传入 GetAnotherObject 方法。有人可以帮助我吗。

最佳答案

来自 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();
    }
}

关于c# - 抽象类中嵌套抽象类及其实现方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785451/

相关文章:

c# - SPUtility.SendEmail 来自地址

php - PHP 抽象静态类方法的替代模型

kotlin - Kotlin 中抽象父类(super class)中的内部类?

c++ - 纯虚方法的模板特化

java - 在java中,嵌套类对象可以使用封闭类方法吗?

Java : size of inner class

c# - 为什么字符串上的 Thread.VolatileRead 无法编译

c# - 检测 PowerPoint 幻灯片是否隐藏

c# - asp.net web应用中是否需要部署.cs和designer.cs文件

c++ - 内部类使用外部类模板参数时(仅当使用 `ostream`时)编译失败