c# - 我是否使用了错误的 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);
}
解决方案
所以我们这里有两个价格:净价(例如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
的 s (28.80
或32.00
: 32.00 - 3.20 == 28.80
)
推荐阅读
- google-cloud-firestore - firestore 子集合中的单调 ID
- java - 插件不反映从关系
- javascript - 以编程方式向 Vue 组件添加属性
- javascript - 在 Javascript 中替换 Sawzip | 在 Windows 中使用 javascript 压缩文件
- python - 将 ansible stdout_lines 导入 python 文件
- ruby-on-rails - 如何在 Shrine 中使用 Upload Endpoint 插件?
- c# - 为什么不能在uwp中使用Added和EnumerationCompleted事件>
- xsd-validation - XML 模式验证问题
- git - 使用 http 代理进行 git 存储库身份验证
- python - PyTorch:来自多个数据集的批处理