2017-10-04 86 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; 
      } 
     } 
    }