2017-10-04 89 views
1

你好我有,因为在Java中,我用来做这在Java中访问从另一个类C#

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

麻烦学习C#的对象字段或属性的总价()方法是用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 
    } 
} 

我不知道我的问题是明确的,但基本上我想知道的是我怎么能达到获取或一组,如果我的对象是一个类的实际值?

+0

'公共双总金额=> product.Price *量;'或旧的语法:'公共双总金额{{返回product.Price *量; }}' – Xiaoy312

回答

1

首先,不使用表达浓郁属性此...只需使用自动属性:

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

最后,你没有明确访问消气,你刚才得到的值的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; 
} 
+0

我想你的意思是'product.Price' – Xiaoy312

+0

@ Xiaoy312是的,没错。谢谢:D –

0

在C#中有属性: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties

和自动实现的属性: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

您可以同时使用实现IR:

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