c# - 从基类执行方法时,如何从派生类中获取要使用的变量?
问题描述
我正在尝试使用从基类继承的两个不同的派生类,每个派生类都有一个彼此不同的布尔变量。布尔值已在基类和派生类中分配。但是,当我从派生类访问仅在基类中声明的方法时,布尔值会导致基类的结果。
我已经尝试在每个类中执行一个方法来初始化其声明的变量。没有进行任何更改。
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
}
}
在跳过 C2 的 if 条件时,我应该从 C1 获得一个 if 语句完成一半。C1 的布尔值应该为真,而 C2 的布尔值应该为假。但是,这两个布尔值都被视为错误。
解决方案
使其成为虚拟财产。当它是虚拟的并且被覆盖时,即使是在基类中定义的代码也会查看当前实例的最覆盖的属性。
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;
}
推荐阅读
- java - log4j 无法在 spring boot resti api 中创建日志文件
- python - 计算两个列表的所有幂集交集
- loopbackjs - Loopback 4 and Mongodb : All model's id are null on response
- shell - 启动需要 sudo 权限的脚本的 Crontab 任务
- reactjs - React 克隆有状态组件
- powershell - 尝试仅从主机名返回 ipv4 地址
- python - Django Reset PW 电子邮件不在 AWS 上发送
- c++ - 拦截 V8 中的任何传出网络请求(在核心级别)
- javascript - 单击按钮时,如何阻止我的 HTML 表格丢失其数据?
- mergesort - 如何仅使用合并排序算法对奇数列表进行排序?还有偶数分开吗?