c#通过其他实例变量设置方法更新实例变量

问题描述 投票:0回答:1

我的作业有问题。我有一个实例变量price,应该具有get方法而没有set方法。我已经通过构造函数计算并分配了这个价格变量。我注意到,如果您将Main中的宽度或高度值更改为另一个数字,则价格变量不会改变。我添加了一个updatePrice()方法,该方法在Main中显式调用时可以使用,但希望通过height / width set方法自动实现。我现在无法使其正常工作。

更改有效宽度变量后,显式调用updatePrice()

using System;
using static System.Console;

class Photo
{
    private int width { get; set; }
    private int height { get; set; }
    protected double price;

    public int Width {
        get
        {
            return width;
        }
        set
        {
            updatePrice(value, height);
            width = value;
        }
    }

    public int Height {
        get
        {
            return height;
        }
        set
        {
            updatePrice(width, value);
            height = value;
        }
    }

    public Photo(int width, int height)
    {
        this.width = width;
        this.height = height;
        if (width == 8 && height == 10)
            price = 3.99;
        else if (width == 10 && height == 12)
            price = 5.99;
        else
            price = 9.99;
    }

    public virtual double Price
    {
        get
        {
            return price;
        }
    }

    public String ToString()
    {
        return GetType() + " with a width of " + width + " and a height of " + height +
            " with a base price of " + Price.ToString("C2");
    }

    // used to be updatePrice() w/ no parameters
    public void updatePrice(int width, int height)
    {
        if (width == 8 && height == 10)
            price = 3.99;
        else if (width == 10 && height == 12)
            price = 5.99;
        else
            price = 9.99;
    }

    static void Main()
    {
        Photo photo = new Photo(10, 12);

        WriteLine(photo.ToString());
        photo.height = 4;
        // updatePrice();
        WriteLine(photo.ToString());
    }
}

[宽度为10高度为12的照片,底价为5.99美元//将高度更改为4宽度为10且高度为4的照片,底价为5.99美元//价格应为$ 9.99

c# oop instance-variables
1个回答
0
投票

[而不是更新价格,而是在Price属性中动态计算价格。这样,您可以确保它始终反映当前状态。

public virtual double Price
{
    get
    {
        if (width == 8 && height == 10) return 3.99;
        if (width == 10 && height == 12) return 5.99;
        return 9.99;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.