简体   繁体   中英

Access to an object field or property from another class c#

Hi I'm having trouble learning c# because in Java I was used to do this in 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;
  }
}

The totalAmount() method is an example with Java of how I use to access an value of an object in another class. How can I achieve the same thing in c#, this is my code

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

I don't know if my question is clear but basically what I want to know is how can I achieve a get or a set if my object is an actual value of one class?

First of all, don't use expression-bodied properties for this... Just use auto-properties:

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

Finally, you don't access the getter explicitly, you just get the value of 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;
}   

In C# you have Properties: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties

And Auto-Implemented properties: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

You can achieve it using both:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM