如何从集合的foreach循环中返回值?

问题描述:

我有两个类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

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

我看到这已经回答了,但我想提供一些额外的说明,如果我可以尝试。 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的属性,如果我的课程中的后端逻辑依赖于其未乘以形式的数字,这可能很有用。在这种情况下,逻辑将更适合于吸气剂。

我希望我不会混淆这个问题。