一个简化的场景。三个类,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 = a
和 B = b
添加到 Child
构造函数来解决它。
这可能吗?如果是怎么办?
我开始查看 base (),但它看起来只能访问 Parent
类而不能访问 GrandParent
。
提前致谢。
附言。如果之前有人问过,我提前道歉,我没有找到任何东西。
快速编辑:我正在努力使解决方案尽可能易于使用,以便进一步开发。
最佳答案
您只能调用直接父类(super class)的构造函数。直接父类(super class)需要公开您需要的选项。它可以使用 protected
构造函数安全地执行此操作。
关于c# - Base Base Constructor C# 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24066917/