我编写了以下多态代码:
public abstract class A
{
readonly int x;
A(int i_MyInt)
{
x = i_MyInt;
}
}
public abstract class B : A
{
//holds few integers and some methods
}
// concrete object class
public class C : B
{
// holds some variables and mathods
C(int MyInt)
{
// here i would like to initialize A's x
}
}
如何从 C 初始化 A 的 x 我尝试将参数传递给 A 的 C'tor - 但没有成功..
请帮忙, 提前致谢 阿米托斯80
最佳答案
您需要向 B 添加一个构造函数,该构造函数接受一个整数并将其传递给 A 的构造函数。然后您可以从 C 调用此构造函数。
public abstract class B : A
{
public B(int myInt) : base(myInt)
{
// other initialization here...
}
}
public class C : B
{
// holds some variables and mathods
public C(int myInt) : base(myInt)
{
// other initialization here...
}
}
A 的构造函数也不能是私有(private)的。
关于c# - 如何在 C# 中将 const 参数传递给抽象类父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4380411/