c# - 带有不影响变量的 if 语句的 Foreach()
问题描述
我正在尝试将 InventoryState 添加到从我之前创建的 IProduct 接口扩展的各种产品中,但是我为检查库存状态所做的 foreach() 语句并未更改属性上 Unassigned 的默认值...
这是每个产品对象的属性:
public string ProductType
{
get { return "Apple"; }
set { }
}
public double BulkPrice
{
get { return 0.99; }
set { }
}
public double RetailPrice
{
get { return 1.49; }
set { }
}
public int Quantity
{
get { return 50; }
set { }
}
public int MaxQuantity
{
get { return 100; }
set { }
}
public InventoryState Status
{
get { return InventoryState.Unassigned; }
set { }
}
这些是有问题的各种声明和foreach:
public enum InventoryState
{
Full,
Selling,
Stocking,
Empty,
Unassigned
}
public interface IProduct
{
string ProductType { get; set; }
double BulkPrice { get; set; }
double RetailPrice { get; set; }
int Quantity { get; set; }
int MaxQuantity { get; set; }
InventoryState Status { get; set; }
}
public static IProduct[] ProductList =
{
new Apple(),
new Blueberry()
};
foreach (IProduct productName in ProductList) // broken- not being called :(?
{
if (productName.Quantity == productName.MaxQuantity)
{
productName.Status = InventoryState.Full;
return productName.Status;
}
else if (productName.Quantity <= (productName.MaxQuantity * (0.5)))
{
productName.Status = InventoryState.Stocking;
}
else if (productName.Quantity == 0)
{
productName.Status = InventoryState.Empty;
}
else
{
productName.Status = InventoryState.Selling;
}
}
解决方案
你总是在你的自动属性中做
get { return "some value";}
即使您为其分配了一个值,即使基础值不同,它也将始终返回“某个值”。
对所有属性执行此操作:
public string ProductType
{
get; set;
} = "Apple";
它们将具有默认值“Apple”,但它会被正确分配和返回。
请注意,自动属性默认值仅从 C# 6.0 开始。
否则,您需要一个私有的支持字段。
推荐阅读
- r - 使用 dplyr::arrange 函数后保留行名的最佳解决方案是什么?
- javascript - React - 模板未注入 HTML 页面
- python - 使用python的列表中相等的所有元素的总和
- node.js - nodejs:Socket io客户端错误:自签名证书
- go - 我可以在共享结构中允许任意字段吗?
- c - SocketCAN长延时收包
- python - 将 S3 存储桶中的 gzip 文件提取到另一个 S3 存储桶
- sql-server - SQL Server 2017 中的情况
- c++ - 脆弱的基类问题会出现在 C++ 中吗?
- intellij-idea - intellij idea 结帐错误:doenst 显示“svn 结帐选项”对话框?