c# - 使用多态对象创建时出现继承错误
问题描述
我有一个 FootWearItem 类和一个 CartItem 类,它们都继承自 ProductItem 类。我还有一个 ShoppingCart 类,其中包含一个包含 CartItems 的列表。
我正在 Main(); 中测试这些类;我正在尝试将 FootWearItems 添加到 ShoppingCart,尽管我似乎收到一条错误消息,指出无法将 ProductItem 转换为 CartItem。
谁能告诉我这是为什么?
public abstract class ProductItem
{
public string ProductCode { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public ProductItem(string productCode, string description, double price)
{
ProductCode = productCode;
Description = description;
Price = price;
}
public override string ToString()
{
return "Product Code: " + ProductCode + "\nDescription: " + Description + "\nPrice: " + Price;
}
}
public enum Gender
{
Men, Women
}
public class FootWearItem : ProductItem
{
public double Size { get; set; }
public Gender Gender { get; set; }
public FootWearItem(string productCode, string description, double price, double size, Gender gender)
: base (productCode, description, price)
{
Size = size;
Gender = gender;
}
public override string ToString()
{
return base.ToString() + "\nSize: " + Size + "\nGender" + Gender;
}
}
public class CartItem : ProductItem
{
public int NumberItems { get; set; }
public CartItem(string productCode, string description, double price, int numberItems)
: base(productCode, description, price)
{
NumberItems = numberItems;
}
}
public class ShoppingCart
{
List<CartItem> cart;
public int MyProperty { get; set; }
private double total;
public ShoppingCart()
{
cart = new List<CartItem>();
}
public void AddItem(CartItem item)
{
if(!cart.Contains(item))
{
cart.Add(item);
}
else
{
throw new ArgumentException("Item is already in cart");
}
}
public double TotalPrice()
{
foreach(CartItem i in cart)
{
total += i.Price;
}
return total;
}
}
public class TestClass
{
public static void Main()
{
ProductItem i1 = new FootWearItem("A122", "black nike shoe", 50.99, 10.5, Gender.Men);
ProductItem i2 = new FootWearItem("A122", "black nike shoe", 70.99, 9.5, Gender.Men);
ProductItem i3 = new FootWearItem("A122", "black nike shoe", 60.99, 6, Gender.Women);
ShoppingCart cart1 = new ShoppingCart();
cart1.AddItem(i1);
cart1.AddItem(i2);
cart1.AddItem(i3);
}
}
干杯
解决方案
您的 CartItem 应该包含 ProductItem 作为属性——就目前而言,ProductItem 不是从 CartItem 派生的,因此不能强制转换。
public class CartItem
{
public int NumberItems { get; set; }
public ProductItem Product { get; set; }
public CartItem(ProductItem product, int numberItems)
{
Product = product;
NumberItems = numberItems;
}
}
推荐阅读
- javascript - 无法使用纱线将 cmd 参数传递给 index.ts
- python - 具有不同用户类型的 Kivy 桌面应用程序
- javascript - Firefox 扩展全局变量和 onInstalled
- c - C中的纸牌 - 卡片符号问题
- java - Java序列化未实现`Serializable`的字段
- java - 在 JAVA 中创建和打印用户列表
- django - 如何为用户引入的过滤器提供 OR 搜索
- react-native - 如何在 map 中设置 if 语句反应?
- terraform - terraform provisioner 无法连接到机器
- powershell - 如何在文件夹名称中使用 var