首页 > 解决方案 > 我是否使用了错误的 set/get 功能?

问题描述

我需要在我的程序中解决这个关于 get/set 函数的问题。

这是完整的未编辑代码: https ://pastebin.com/Vd8zC51m

编辑:我的好朋友找到了解决方案,即像这样使用“价值”:

        {
            get
            {
                return this.returnValue;
            }

            set
            {
                if (value > 30)
                {
                    this.returnValue = value - (value * 0.10f);
                } else
                {
                    this.returnValue = value;
                }
            }
        }

如果我浪费了任何人的时间,我很抱歉......!

问题是这样的:使用 set/get 创建一个价格属性,如果价格超过 30,则返回降低 10% 的价格。

我得到的是:值为 0。

我知道出了什么问题,只是不知道如何解决。我知道它在 set 命令中。在我展示代码之后,您可能会有更好的理解。

我尝试在互联网上搜索如何正确使用 set 命令,并尝试了不同的方法来执行 set 命令。

public class Book
{
    public string Name;
    public string writerName;
    public string bPublisher;
    public float bPrice;
    public string bTheme;
    public float returnValue;

    public Book(string name, string writer, string publisher, float price, string theme)
    {
        Name = name;
        writerName = writer;
        bPublisher = publisher;
        bPrice = price;
        bTheme = theme;
    }

    public float Price
    {
        get
        {
            return returnValue;
        }

        set
        {
            if (this.bPrice > 30)
            {
                returnValue = this.bPrice - (this.bPrice * 0.10f);
            } else
            {
                returnValue = this.bPrice;
            }
        }
    }
}

----------这些是从程序中删除的主要部分----------

static void Main(string[] args)
{
    Book k2 = new Book("A book", "O. Writer", "Publisher Ab", 36.90f, "Fantasy");
    Console.WriteLine(k2.Price);
}

标签: c#class

解决方案


所以我们这里有两个价格:净价(例如45.00)和降价45.00 - 4.50 == 41.50

public Book {
  ...
  const Decimal PriceThreshold = 30.0m;
  const Decimal ReducePerCent = 10.0m; 

  private Decimal m_NetPrice;

  // Net price
  // Decimal (not Single, Double) usually is a better choice for finance
  public Decimal NetPrice {
    get {
      return m_NetPrice;
    }
    set {
      if (value < 0) 
        throw new ArgumentOutOfRangeException(nameof(value));

      m_NetPrice = value;
    }
  }  

  // Price with possible reduction
  public Decimal Price {
    get {
      return NetPrice > PriceThreshold 
        ? NetPrice - NetPrice / 100.0m * ReducePerCent
        : NetPrice;
    } 
  } 
}

请注意,我们没有 财产setPrice歧义,因为一个Price,比如说,28.80对应于两个有效NetPrice的 s (28.8032.00: 32.00 - 3.20 == 28.80


推荐阅读