2014-02-11 60 views
0

我可以用下面的方式動態更新列表,例如總量= firstamount + secondamount ?.如果沒有,那麼做到這一點最理想的方法是什麼?在對象初始值設定項列表中執行算術運算c#

List<Test> test = new List<Test> 
{ 
    new Test 
    { 
     Name ="ABC", 
     FirstAmount = 10, 
     SecondAmount = 20, 
     TotalAmount = FirstAmount + SecondAmount                         
    } 
};  

public class Test 
{ 
    public String Name { get; set; } 

    public decimal FirstAmount { get; set; } 

    public decimal SecondAmount { get; set; } 

    public decimal TotalAmount { get; set; } 
} 

回答

2

如果你的總數將總是其他兩個的總和,你可以這樣做:

List<Test> test = new List<Test> 
{ 
    new Test { Name ="ABC",FirstAmount =10,SecondAmount =20} 
}; 

public class Test 
{ 
    public String Name {set;get;} 

    public decimal FirstAmount {set;get;} 

    public decimal SecondAmount {set;get;} 

    public decimal TotalAmount { get { return FirstAmount + SecondAmount; } } 
} 
+0

我如何得到「total金額價值「列入清單說,如果我想將列表綁定到網格。我如何訪問類中的對象? – Yoda

+0

只需使用'TotalAmount'屬性。你希望該字段是可編輯的嗎? – ivowiblo

+0

假設我有一個List列表對象的集合,如列表 test = new列表 { {Test = {ABC},FirstAmount = 10,SecondAmount = 20} New Test {Name =「XYZ」,FirstAmount = 20, SecondAmount = 30} };在這種情況下,我該如何調用財產,因爲這將被綁定到網格 – Yoda

0

不,您不能訪問被初始化的對象的屬性,除了設置它們。

在這種情況下,最簡單的解決方法是使用中間變量:

int firstAmount = 10; 
int secondAmount = 20; 

List<Test> test = new List<Test> 
{ 
    new Test { Name ="ABC",FirstAmount = firstAmount,SecondAmount = secondAmount ,TotalAmount = firstAmount + secondAmount} 
}; 
+0

我知道這個解決方法,但我很好奇,如果我們能以上述方式做 – Yoda

4

您可以更改對象使其在TotalAmount吸氣...像

List<Test> test = new List<Test> 
{ 
    new Test { Name ="ABC",FirstAmount =10,SecondAmount =20} 
}; 

public class Test 
{ 
    public String Name {set;get;} 

    public decimal FirstAmount {set;get;} 

    public decimal SecondAmount {set;get;} 

    public decimal TotalAmount {get {return FirstAmount + SecondAmount;}} 
} 
+0

@Magus完成 - 我從OP的貼子複製代碼並重新粘貼它香草:) – Jay

0

A反璞歸真的方法是使用一個構造函數:

List<Test> test = new List<Test> 
{ 
    new Test(
     name: "ABC", 
     firstAmount: 10, 
     secondAmount: 20                        
    ) 
};  

public class Test 
{ 
    public Test(string name, decimal firstAmount, decimal secondAmount) 
    { 
     Name = name; 
     FirstAmount = firstAmount; 
     SecondAmount = secondAmount; 
     TotalAmount = firstAmount + secondAmount; 
    } 

    public String Name { get; set; } 

    public decimal FirstAmount { get; set; } 

    public decimal SecondAmount { get; set; } 

    public decimal TotalAmount { get; set; } 
} 

白衣這種方法,您TotalAmount屬性保持編輯。

+0

如何將「TotalAmount」值返回到列表中以將其綁定到網格? – Yoda

+0

您可以發佈您用於標識不起作用的網格的代碼嗎?我不理解你的問題 – ivowiblo