2017-05-29 127 views
-1

我有兩個類InvoiceInvoiceProductsInvoiceProducts是一個集合,並且只有一個名爲Price的屬性,並且我想要Invoice擁有一個名爲TotalPrice的屬性,該屬性將返回InvoiceProducts集合中的Price foreach項添加到它。不過,我不確定要這樣做。用目前的方法,我試圖使用它,我得到一個錯誤,說如何從集合的foreach循環中返回值?

「對象引用未設置爲對象的實例。」有沒有辦法做到這一點?

電流方式:

public class Invoice 
{ 
    public int InvoiceID { get; set; } 
    public string ClientName { get; set; } 
    public DateTime Date { get; set; } = DateTime.Today; 
    private decimal totalPrice; 
    public decimal TotalPrice { 
     get 
     { 
      return totalPrice; 
     } 
     set 
     { 
      foreach(var item in InvoiceProducts) 
      { 
       totalPrice += item.Price; 
      } 
     } 
    } 

    public virtual ICollection<InvoiceProducts> InvoiceProducts { get; set; } 
} 

public class InvoiceProducts 
{ 
    public int InvoiceProductsID { get; set; } 
    public int InvoiceID { get; set; } 
    public int ProductID { get; set; } 
    public int ProductQuantity { get; set; } 
    public decimal Price { get { return Product.ProductPrice * ProductQuantity; } } 

    public virtual Invoice Invoice { get; set; } 
    public virtual Product Product { get; set; } 
} 
+0

爲InvoiceProducts添加init(例如公共虛擬ICollection InvoiceProducts {get; set;} = new List ();) –

+0

您也可以刪除TotalPrice的set部分並僅使用get(當然,計算回答之前) –

+0

可能重複[什麼是NullReferenceException,以及如何解決它?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i -修理它) – dymanoid

回答

3
public decimal TotalPrice { 
    get 
    { 
     return InvoiceProducts.Sum(product => product.Price); 
    } 
} 

或短,因爲它是唯一獲得:

public decimal TotalPrice => InvoiceProducts.Sum(product => product.Price); 

當然,你需要初始化你的產品清單,並可能使它獲得只要。

public Invoice() 
{ 
    InvoiceProducts = new List<InvoiceProcuct>(); 
} 

public ICollection<InvoiceProduct> InvoiceProducts { get; } 
0

我看到這已經回答了,但我想提供一些額外的說明,如果我可以嘗試。 A set需要參數,並且是您希望在分配屬性值時運行的特殊邏輯,具體取決於分配的內容。舉一個簡單的例子:

public class SpecialNumber 
    { 
     private double _theNumber; 

     public double TheNumber 
     { 
      get { return _theNumber; } 
      set 
      { 
       _theNumber = value * Math.PI; 
      } 
     } 
    } 

保留字value是表達式的右手側:

specialNumberObject.TheNumber = 5.0; 

這樣,值將在5.0的設定器的內部。由S. Spindler指定的邏輯在get中是完美的,因爲它定義了一個自定義返回,您希望在任何時候想要執行訪問屬性的值。

我的課程的另一個版本可能會決定在出門時有一個乘以PI的屬性,如果我的課程中的後端邏輯依賴於其未乘以形式的數字,這可能很有用。在這種情況下,邏輯將更適合於吸氣劑。

我希望我不會混淆這個問題。