在对象初始值设定项列表 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; }
}

你能改变你的对象,让它成为TotalAmount的getter吗?类似的东西

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

如果您的总数始终是其他两个的总和,则可以这样做:

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

不,您不能访问正在初始化的对象的属性,除非设置它们。

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

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

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

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

最新更新