c# - Base Base Constructor C# 初始化

标签 c# inheritance

一个简化的场景。三个类,GrandParent,Parent 和 Child。我想要做的是利用 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 () {}
}

子类,出现问题。

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

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

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

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

提前致谢。

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

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

最佳答案

您只能调用直接父类(super class)的构造函数。直接父类(super class)需要公开您需要的选项。它可以使用 protected 构造函数安全地执行此操作。

关于c# - Base Base Constructor C# 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24066917/

相关文章:

c# - 如何正确测试抽象类

c# - TextBlock 附加属性绑定(bind)

c# - 使用 xamarin.forms 的 iOS 应用程序链接

c# - 如何在子类中覆盖 .NET Framework 类的属性?

c++ - Qt MetaObject 从单独的动态库继承检查

继承方法的phpdoc

c# - 使用 docker-compose 使用 dotnet 核心的 MongoDB 连接超时

c# - MongoCursor.Count 与... IAsyncCursor.Count?

c++ - 返回不同类型的变量

c++ - 没有成员函数的结构的继承