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

3

你好,我在学习C#时遇到了一些困难,因为在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
  }   
}

我不知道我的问题是否清晰,但基本上我想知道的是,如果我的对象是一个类的实际值,我如何实现获取或设置?


public double TotalAmount => product.Price * quantity; or in old syntax: public double TotalAmount { get { return product.Price * quantity; } } - Xiaoy312
2个回答

6

首先,不要使用表达式体属性来实现这个功能... 直接使用自动属性:

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;
}   

我认为你指的是 product.Price - Xiaoy312

3
在C#中,您有属性(Properties): https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties 还有自动实现的属性(Auto-Implemented properties): https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties 使用这两种方式均可实现。
    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;
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接