具有if语句的Foreach()不影响变量

时间:2019-04-15 13:58:59

标签: c# 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;
                }
            }

1 个答案:

答案 0 :(得分:1)

您总是会在自动属性中这么做

get { return "some value";}

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

对您的属性所有执行此操作:

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

它们将具有默认值“ Apple”,但将得到分配并正确返回。

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

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