c# - C# - 基类的访问字段
问题描述
我有一个基类和派生类,其中我在基类中有一个布尔变量。现在检查派生类中的变量时,布尔变量的值始终为 False。
public class RainingQuestion
{
public virtual bool raining { get; set; }
public virtual string Answer(int elementToTest)
{
if (elementToTest < 176)
{
raining = false;
return ("It's not raining.");
}
else
{
raining = true;
return ("It's raining.");
}
}
}
public class WindSpeedQuestion : RainingQuestion
{
public override bool raining { get; set; }
public override string Answer(int elementToTest)
{
//bool _raining = this.raining;
if (elementToTest > 15)
{
if (!raining)
{
return("You can fly your kite. Wind speed is at " + elementToTest + "kph.");
}
else
{
return("Don't fly your kite. It's raining.");
}
}
else
{
return("Don't fly kite. Wind Speed not strong. Wind speed is at " + elementToTest + "kph.");
}
}
}
程序.cs
RainingQuestion ques1 = new RainingQuestion();
WindSpeedQuestion ques3 = new WindSpeedQuestion();
Console.WriteLine(ques1.Answer(180));
Console.WriteLine(ques3.Answer(16));
在此示例中,ques3.Answer 必须返回“不要放风筝。正在下雨”,因为 ques1 中的下雨变量为 true,并且 ques3 中的给定参数大于 15,但 ques3 中的布尔变量始终返回 False .
我可以知道我可能会错过什么吗?
解决方案
原因是ques1
和ques3
是类的不同实例。
您raining = true;
在第一次调用中设置了 ques1 Answer()
,但 ques3 是与 ques1 完全不同的对象,因此下雨将是错误的,因为在 ques3 中您从未设置过它。
把它想象成现实生活中的样子。假设你有两支铅笔。一个在你的左手,一个在你的右手。它们都是铅笔,但它们是不同的对象。左手的铅笔可能很锋利,而右手的铅笔则不锋利。左边可能是蓝色,右边可能是红色。把右边的铅笔磨得更锋利,不会让左边的铅笔更锋利。
在您的代码中,这些行
RainingQuestion ques1 = new RainingQuestion();
WindSpeedQuestion ques3 = new WindSpeedQuestion();
意味着您正在创建一个对象的两个不同版本。对 ques1 的任何更改都不会影响 ques3,因为就像每只手中的铅笔一样,它们是不同的东西。
推荐阅读
- c# - 在 C# 的 Try 块中,如果在我的文本框中输入了一个 int,我希望抛出异常的 catch 部分?
- java - 升级到 6.0.1 后,Exe4j 闪屏不会消失
- angular - Angular 6 中的 datatables.net 编辑器使用
- php - PHP不编辑文本文件?
- java - Java - 如何使用货币格式将字符串转换为大十进制
- html - 单选按钮和标签封闭
标签显示在同一行(仅使用 HTML)</h1> <div id="body"><p>我希望我的单选按钮和标签位于同一水平行。我正在使用 xmp 标记将原始 html 显示为带有单选按钮的选项。但是 xmp 中的文本以新行开头。有没有 xmp 标签的替代品。</p> <pre><code> `<input class="answer" type="radio" name="q3" value="0" - asp.net - CSV 文件到 DataTable 到 SQL Server
- html - 为什么 CSS 媒体查询以错误的方式工作?
- php - 在 Xampp 中安装扩展
- php - laravel中的自动递增数字