首页 > 解决方案 > 带有不影响变量的 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;
                }
            }

标签: c#foreach

解决方案


你总是在你的自动属性中做

get { return "some value";}

即使您为其分配了一个值,即使基础值不同,它也将始终返回“某个值”。

对所有属性执行此操作:

 public string ProductType
        {
            get; set;
        } = "Apple";

它们将具有默认值“Apple”,但它会被正确分配和返回。

请注意,自动属性默认值仅从 C# 6.0 开始。

否则,您需要一个私有的支持字段。


推荐阅读