从另一个类 C# 访问对象字段或属性

jea*_*182 2 c#

嗨,我在学习 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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
  }   
}
Run Code Online (Sandbox Code Playgroud)

我不知道我的问题是否清楚,但基本上我想知道的是,如果我的对象是一个类的实际值,我如何实现 get 或 set ?

Mat*_*zer 5

首先,不要为此使用表达式实体属性......只需使用自动属性:

public class Product
{
  public double Price { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

最后,您不会显式访问 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;
}   
Run Code Online (Sandbox Code Playgroud)