2015-04-27 56 views
0

我試圖將屬性添加到Add()方法,但它似乎不工作。我確定我錯過了一些東西。將屬性添加到Add()方法

Items.Add(new ItemProperties 
        { 
         Item = Convert.ToInt32(lines[i]), 
         Description = lines[i + 1], 
         Quantity = Convert.ToInt32(lines[i + 2]), 
         UnitPrice = Convert.ToInt32(lines[i + 3]), 
         Tax = Convert.ToInt32(lines[i + 4]), 
         TotalTax = 34234, 
         Total //<-- Error: Invalid initializer member declarator 

        }); 

ItemProperties類:

public class ItemProperties 
     { 
      public int Item { get; set; } 
      public string Description { get; set; } 
      public int Quantity { get; set; } 
      public int UnitPrice { get; set; } 
      public int Tax { get; set; } 
      public int TotalTax { get; set; } 
      public int Total { 
       get 
       { 
        return Quantity * UnitPrice; 
       } 
       set 
       { 
       } 
      } 
     } 

我得到兩個錯誤:

無效的初始成員聲明

'合計' 的名稱不在當前情況下存在

我想什麼Total財產做的是的Quantity * UnitPrice結果添加到Add()方法

+5

只需刪除該行,它沒有任何意義。擺脫空調也是如此。 –

+0

@HansPassant謝謝! –

+0

您不希望_「將Quantity * UnitPrice的結果添加到Add()方法」_中。你希望'Total'自動返回'Quantity * UnitPrice',它已經做到了。 –

回答

2
public int Total 
{ 
    get 
    { 
     return Quantity * UnitPrice; 
    } 
    set 
    { 
    } 
} 

變化

public int Total 
{ 
    get 
    { 
     return Quantity * UnitPrice; 
    } 
} 

您可以使用屬性,只有吸氣劑

+0

添加屬性時刪除總字段。 – Thijs

0

你沒有爲Total設置setter,但是嘗試爲它設置一些值。所以我建議在初始化邏輯中實現setter或刪除Total的使用

public int Total { 
       get 
       { 
        return Quantity * UnitPrice; 
       } 
       set 
       { 
        // you need to add some code 
       }