繁体   English   中英

如何使用不在基类中的属性

[英]How to use properties that are not in the base class

基类

public class Base
    {
        public int Price { get; set; }
        public string Name { get; set; }

        public int Tax()
        {
            return Price / 2;
        }
    }

派生类

public class Car : Base
{
    public int Power { get; set; }
    public string Brand { get; set; }

    public Car(string brand, int power, int price, string name)
    {
        Brand = brand;
        Power = power ;
        Price = price;
        Name = name;
    }

购物车类

 public class Cart
    {
        private List<Base> list = new List<Base>();
        public int TotalPrice()
        {
            int sumPrice = 0;
            foreach (Base item in list)
            {
                sumPrice += item.Tax();
            }
            return sumPrice;
        }
        public void Add(Base baseClass)
        {
            list.Add(baseClass);
        }

控制器

     Cart cart = new Cart();
     Car car = new Car("BMW", 10, 100, "John");
     cart.Add(car);
     return View("Index", cart.TotalPrice().ToString());

我从派生类创建对象并将其添加到购物车。

Car car = new Car("BMW", 10, 100, "John");

但是当我在 Cart 类中列出汽车时,我使用基类。

private List<Base> list = new List<Base>();

我没有收到任何错误,但我想知道的是,即使基类中没有“Brand”和“Power”属性,我仍然可以将它们添加到基类并列出它们。

public void Add(Base base)

{

list.Add(base);

}

从继承来看,一个Car是一个Base ,所以它可以被添加到list (一个List<Base> )。

仍然可以将它们添加到基类... BrandPowerCar属性,而不是Base

并列出它们... BrandPowerCar制造之后的任何地方都没有被引用。 如果您尝试,看看会发生什么:

    public int TotalPrice()
    {
        int sumPrice = 0;
        foreach (Base item in list)
        {
            sumPrice += item.Tax();
            item.Power = 42; // <--- try to add this line
        }
        return sumPrice;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM