在我的程序中有一个关于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.80
或 32.00
:32.00 - 3.20 == 28.80
)
关于c# - 我是否使用了错误的设置/获取功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56143869/