基类 基类构造函数 C# 初始化

Emz*_*Emz 2 c# inheritance

一个简化的场景。三个班级,祖父母,父母和孩子。我想要做的是利用 GrandParent 和 Parent 构造函数来初始化 Child 实例。

class GrandParent ()
{
    public int A {get; protected set;}
    public int B {get; protected set;}

    public GrandParent (int a, int b);
    {
        A = a;
        B = b;
    }
}

class Parent : GrandParent ()
{
    public Parent () {}
}
Run Code Online (Sandbox Code Playgroud)

子类,出现问题。

class Child : Parent ()
{
    public int C {get; protected set}

    public Child (int c) // here I want it to also call the GrandParent (int a, int b)
                         // before calling Child (int c)
    {
        C = c;
    }
}

Child = new Child (1,2,3);
Run Code Online (Sandbox Code Playgroud)

我想要的是变量 a、b 和 c 分别获得 1,2 3 作为值。我知道我可以通过简单地将A = aB = b添加到Child构造函数来解决它。

这可能吗?如果是这样怎么办?

我开始查看 base() 但看起来它只能访问该类Parent,而不能访问GrandParent.

提前致谢。

附言。如果之前有人问过,我提前道歉,我没有找到任何东西。

快速编辑:我正在努力使解决方案尽可能易于使用,以进一步开发。

Dan*_*ite 5

您只能调用直接超类的构造函数。直接超类需要公开您需要的选项。它可以使用protected构造函数安全地完成此操作。