我正在尝试使用从基类继承的两个不同的派生类,每个派生类都有一个与另一个不同的布尔变量。 boolean已在基类和派生类中分配。但是,当我从仅在基类中声明的派生类访问方法时,布尔值会导致基类的结果。
我已经尝试在每个初始化其声明变量的类中执行一个方法。没有改变。
public partial class Form2 : Form
{
public class BaseC : Form
{
public bool reversePlace = false;
public void computeInput(BaseC cc)
{
if (reversePlace)
{
//Execute condition
if (cc.reversePlace)
{
//Execute execution from other derived class
}
}
}
}
public class DerivedC1 : BaseC
{
public bool reversePlace = true;
}
public class DerivedC2 : BaseC
{
public bool reversePlace = false;
}
DerivedC1 C1 = new DerivedC1();
DerivedC2 C2 = new DerivedC2();
public Form2()
{
C1.computeInput(C2); //Should execute first condition for being true while ignoring the inner condtion for being false
}
}
我应该从C1中途获得一个if语句,同时跳过C2的if条件。 C1的布尔值应为true,而C2应为false。然而,两个布尔都被认为是假的。
使它成为虚拟财产。当它被虚拟化并被覆盖时,即使在基类中定义的代码也会查看当前实例的被覆盖最多的属性。
public class BaseC : Form
{
public virtual bool ReversePlace => false;
//etc....
}
public class DerivedC1 : BaseC
{
public override bool ReversePlace => true;
}
public class DerivedC2 : BaseC
{
public override bool ReversePlace => false;
}
我需要一些时间来研究继承,特别是虚拟属性和方法,以及如何覆盖它们。
您的基类通常应该在必要时使用关键字virtual和覆盖子方法和类。
这是一个链接,可以帮助您获得一般的想法:https://www.c-sharpcorner.com/UploadFile/3d39b4/virtual-method-in-C-Sharp/
如果您只想设置值,而不是从基类隐藏继承的成员,则可以在构造函数中执行此操作。
...
public class DerivedC1 : BaseC
{
public DerivedC1()
{
this.reversePlace = true;
}
}
public class DerivedC2 : BaseC
{
public DerivedC2()
{
this.reversePlace = false;
}
}
...