首页 > 解决方案 > 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 .

我可以知道我可能会错过什么吗?

标签: c#

解决方案


原因是ques1ques3是类的不同实例。

raining = true;在第一次调用中设置了 ques1 Answer(),但 ques3 是与 ques1 完全不同的对象,因此下雨将是错误的,因为在 ques3 中您从未设置过它。

把它想象成现实生活中的样子。假设你有两支铅笔。一个在你的左手,一个在你的右手。它们都是铅笔,但它们是不同的对象。左手的铅笔可能很锋利,而右手的铅笔则不锋利。左边可能是蓝色,右边可能是红色。把右边的铅笔磨得更锋利,不会让左边的铅笔更锋利。

在您的代码中,这些行

    RainingQuestion ques1 = new RainingQuestion();
    WindSpeedQuestion ques3 = new WindSpeedQuestion();

意味着您正在创建一个对象的两个不同版本。对 ques1 的任何更改都不会影响 ques3,因为就像每只手中的铅笔一样,它们是不同的东西。


推荐阅读