在继承的类中设置变量

时间:2017-01-15 19:57:07

标签: c#

我有一个问题,我有两种类型的Topping类,一个普通的“Topping”类,一个继承自Topping并添加一个SpiceLevel,称为“SpicyTopping”。

我的问题是每当我构造一个SpicyTopping对象时,SpiceLevel都设置为0,我必须在构造对象后手动设置它

 //Objects
            Topping Mozzarella = new Topping("Mozzarella", 0.40f);
            Topping Ham = new Topping("Ham", 0.60f);
            Topping Eggs = new Topping("Eggs", 0.70f);
            Topping Salmon = new Topping("Salmon", 0.98f);
            Topping Tuna = new Topping("Tuna", 0.80f);
            Topping Garlic = new Topping("Garlic", 0.20f);
            Topping Beef = new Topping("Beef", 0.90f);
            Topping Chicken = new Topping("Chicken", 0.95f);
            SpicyTopping SweetChiliPeppers = new SpicyTopping("Sweet Chili Peppers", 0.31f, 1);//Mild
            SpicyTopping CayenneChiliPeppers = new SpicyTopping("Cayenne Chili Peppers", 0.32f, 2);//Moderate
            SpicyTopping HabaneroChiliPeppers = new SpicyTopping("Habanero Chili Peppers", 0.33f, 3);//Ferocious
            SweetChiliPeppers.ToppingSpiceLevel = 1;
            CayenneChiliPeppers.ToppingSpiceLevel = 2;
            HabaneroChiliPeppers.ToppingSpiceLevel = 3;

我不明白为什么我必须这样做,因为我认为构造函数设置正确

namespace AnotherTest
{
    public class Topping
    {
        //Private Variables
        private string toppingName;
        private float toppingPrice;

        //Properties
        //Topping Name
        public string ToppingName
        {
            get { return toppingName; }
            set { toppingName = value; }
        }

        //Topping Price
        public float ToppingPrice
        {
            get { return toppingPrice; }
            set { toppingPrice = value; }
        }

        //Constructor
        public Topping(string toppingName, float toppingPrice)
        {
            ToppingName = toppingName;
            ToppingPrice = toppingPrice;


        }
    }

    class SpicyTopping : Topping
    {
        //Private Variables
        private int toppingSpiceLevel;

        //Properties
        public int ToppingSpiceLevel
        {
            get { return toppingSpiceLevel; }
            set { toppingSpiceLevel = value; }
        }
        //Constructor
        public SpicyTopping(string toppingName,
                            float toppingPrice,
                            int ToppingSpiceLevel)
               : base(toppingName, toppingPrice)
        {
            ToppingName = toppingName;
            ToppingPrice = toppingPrice;
            ToppingSpiceLevel = toppingSpiceLevel;
        }
    }
}

问题是什么?谢谢你的帮助

2 个答案:

答案 0 :(得分:3)

在构造函数中,您定义的变量不正确。

ToppingSpiceLevel = toppingSpiceLevel;

应该是:

toppingSpiceLevel = ToppingSpiceLevel;

属性ToppingSpiceLevel是用于公开顶部spice级别的属性,但是私有变量toppingSpiceLevel需要在构造函数级别正确设置,如上所示。

答案 1 :(得分:0)

您已在构造函数定义中大写ToppingSpiceLevel