在对象初始化列表c#中执行算术运算

时间:2014-02-11 20:01:03

标签: c# .net list

我可以通过以下方式动态更新列表,例如总金额= firstamount + secondamount吗?如果没有,最理想的方法是什么?

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

4 个答案:

答案 0 :(得分: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;}}
}

答案 1 :(得分: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; } }
}

答案 2 :(得分:0)

不,除了设置它们之外,您无法访问正在初始化的对象的属性。

在这种情况下,最简单的解决方法是使用中间变量:

int firstAmount = 10;
int secondAmount = 20;

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

答案 3 :(得分:0)

另一种方法是使用构造函数:

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属性仍然可以编辑。