简体   繁体   中英

How to use properties that are not in the base class

Base Class

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

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

Derived Class

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;
    }

Cart Class

 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);
        }

Controller

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

I create objects from a derived class and add it to the cart.

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

But I use base class when I list cars in Cart class.

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

I don't get any errors, but what I want to know is that even though there are no "Brand" and "Power" properties in the base class, I can still add them to the base class and list them.

public void Add(Base base)

{

list.Add(base);

}

From inheritance, a Car is-a Base , so it can be added to list (a List<Base> ).

can still add them to the base class... Brand and Power are properties of Car , not Base .

and list them... Brand and Power are not referenced anywhere after the construction of a Car . See what happens if you try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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