【问题标题】:How to use properties that are not in the base class如何使用不在基类中的属性
【发布时间】:2020-10-05 21:46:56
【问题描述】:

基类

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 = new Car("BMW", 10, 100, "John");

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

私有列表 list = new List();

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

public void Add(Base base)

{

list.Add(base);

}

【问题讨论】:

  • 只需将基类转换为 car 即可访问属性。

标签: c# asp.net oop polymorphism


【解决方案1】:

从继承,一个Car is-a Base,所以它可以添加到list(一个List&lt;Base&gt;)。

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

并列出它们... BrandPower 在构造 Car 之后的任何地方都不会被引用。看看如果你尝试会发生什么:

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

【讨论】:

  • 我不能在 Cart 类中使用“Power”和“Brand”属性,但是当我在调试模式下运行它时,我会在列表中看到“Power”和“Brand”属性添加方法。 i.imgur.com/YwHogLz.jpeg 抱歉,我是新手,所以我无法理解一些 OOP 概念。
  • 不用担心 - 调试会显示实例的所有属性。恰好实例是Car。但是,该列表属于List&lt;Base&gt;,因此该列表中的每个项目is-a Base。但列表中的每一项不一定都是Car。尝试添加另一个扩展 Base 的类,例如 Food,并具有自己的属性,例如 ServingsPerCcontainerCaloriesPerServing。查看 cast 和 instanceof,但要小心,因为使用它们通常表明存在设计问题。
  • 谢谢,您的帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2023-03-23
  • 2010-11-04
  • 2013-10-17
  • 1970-01-01
相关资源
最近更新 更多