嗨,我在学习c#时遇到了麻烦,因为在Java中我习惯用Java来做这个。
public class Product
{
private double price;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class Item
{
private int quantity;
private Product product;
public double totalAmount()
{
return product.getPrice() * quantity;
}
}
totalAmount()方法是Java的一个示例,用于访问另一个类中对象的值。如何在c#中实现相同的功能,这是我的代码
public class Product
{
private double price;
public double Price { get => price; set => price = value; }
}
public class Item
{
private int quantity;
private Product product;
public double totalAmount()
{
//How to use a get here
}
}
我不知道我的问题是否清楚,但基本上我想知道的是,如果我的对象是一个类的实际值,我该如何实现get或set?
答案 0 :(得分:1)
首先,不要为此使用表达式身体属性...只需使用自动属性:
public class Product
{
public double Price { get; set; }
}
最后,您没有明确访问getter,只是获得Price
的值:
public double totalAmount()
{
// Properties are syntactic sugar.
// Actually there's a product.get_Price and
// product.set_Price behind the scenes ;)
var price = product.Price;
}
答案 1 :(得分:0)
你可以使用两者来实现:
public class Product
{
public decimal Price { get; set; }
}
public class Item
{
public Product Product { get; set; }
public int Quantity { get; set; }
public decimal TotalAmouint
{
get
{
//Maybe you want validate that the product is not null here.
return Product.Price * Quantity;
}
}
}