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

C# 从另一个c类访问对象字段或属性#,c#,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 qu

嗨,我在学习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?

首先,不要使用表达式体属性来实现此功能。。。只需使用自动属性:

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;
}   
在C#中,您具有以下属性:

和自动实现的属性:

您可以使用以下两种方法来实现:

    public class Product
    {
        public decimal Price { get; set; }
    }

    public class Item
    {
        public Product Product { get; set; }

        public int Quantity { get; set; }

        public decimal TotalAmount
        {
            get
            {
                // Maybe you want validate that the product is not null here.
                // note that "Product" here refers to the property, not the class
                return Product.Price * Quantity;
            }
        }
    }

public double TotalAmount=>产品价格*数量
或旧语法:
public double TotalAmount{get{return product.Price*quantity;}}}
我想你的意思是
product.Price