c# - 我是否使用了错误的设置/获取功能?

标签 c# class

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

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

编辑:我的好 friend 找到了解决方案,就是像这样使用“值”:

        {
            get
            {
                return this.returnValue;
            }

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

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

问题是这样的: 使用 set/get 创建一个 Price 属性,如果价格超过 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);
}

最佳答案

所以我们这里有两个价格:净价(例如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;
    } 
  } 
}

请注意,我们没有 set Price 属性;存在歧义,因为一个Price,比如说,28.80 对应于两个 有效的NetPrice (28.8032.00:32.00 - 3.20 == 28.80)

关于c# - 我是否使用了错误的设置/获取功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56143869/

相关文章:

c# - 将 VlcManager 与最新版本的 Vlc.DotNet 一起使用

c# - 使用 Messsage Service Client for .net 连接到 IBM WMQ 时如何传递身份验证信息

c# - 派生 FixedDocument 的序列化

c# - 在 C# 中搜索 Windows 用户 SID

c# - 我可以覆盖 C# 中的属性吗?

java - 在 IntelliJ 中,查看类/接口(interface)的所有后代的快捷方式?

java - 具有可变参数的多个构造函数

c# - Try/Catch——我怎么知道在奇怪/复杂的情况下要捕捉什么?

java - 使用泛型时,javac 编译器是否为每种类型创建不同的类?

class - 如何使用元对象协议(protocol)向对象添加属性?