2013-05-21 77 views
6

我想改变我的列表中的货币价值,但我总是得到一个错误信息:无法修改列表中的结构?

不能修改的“System.Collections.Generic.List.this [INT]”的返回值,因为它是不是变量

什么是错?我如何改变价值?

struct AccountContainer 
{ 
    public string Name; 
    public int Age; 
    public int Children; 
    public int Money; 

    public AccountContainer(string name, int age, int children, int money) 
     : this() 
    { 
     this.Name = name; 
     this.Age = age; 
     this.Children = children; 
     this.Money = money; 
    } 
} 

List<AccountContainer> AccountList = new List<AccountContainer>(); 

AccountList.Add(new AccountContainer("Michael", 54, 3, 512913)); 
AccountList[0].Money = 547885; 

回答

8

您已声明AccountContainerstruct。所以

AccountList.Add(new AccountContainer("Michael", 54, 3, 512913)); 

创建的AccountContainer一个新实例,并将该实例到列表中的副本;和

AccountList[0].Money = 547885; 

检索第一个项目的列表中的一个副本,改变副本的Money场,并丢弃副本–的第一个项目在列表中保持不变。由于这显然不是你想要的,所以编译器会提醒你。

解决方案:不要创建可变的struct s。创建一个不可变的struct(即创建后无法更改的创建)或创建一个class

9

您正在使用evil可变结构。

更改为一个类,一切都会正常工作。

+2

可惜关于'Point',''Rectangle''和'Size'。至少微软在制作'Complex'之前学会了一点。如果*是可变的,那将会非常令人讨厌。 –

0

也许不推荐,但它解决了这个问题:

AccountList.RemoveAt(0); 
AccountList.Add(new AccountContainer("Michael", 54, 3, 547885)); 
+0

删除列表中的第一个项目需要将所有项目移动到索引中,然后添加项目需要将其移回。相反,你应该在该索引处设置值:'list [index] = new ...;' – Servy

+0

好点 - 我没有试图维护列表顺序。 – bigtech

1

这是我会怎么解决它为您的方案(使用不变struct方法,而不是将其更改为class):

struct AccountContainer 
{ 
    private readonly string name; 
    private readonly int age; 
    private readonly int children; 
    private readonly int money; 

    public AccountContainer(string name, int age, int children, int money) 
     : this() 
    { 
     this.name = name; 
     this.age = age; 
     this.children = children; 
     this.money = money; 
    } 

    public string Name 
    { 
     get 
     { 
      return this.name; 
     } 
    } 

    public int Age 
    { 
     get 
     { 
      return this.age; 
     } 
    } 

    public int Children 
    { 
     get 
     { 
      return this.children; 
     } 
    } 

    public int Money 
    { 
     get 
     { 
      return this.money; 
     } 
    } 
} 

List<AccountContainer> AccountList = new List<AccountContainer>(); 

AccountList.Add(new AccountContainer("Michael", 54, 3, 512913)); 
AccountList[0] = new AccountContainer(
    AccountList[0].Name, 
    AccountList[0].Age, 
    AccountList[0].Children, 
    547885); 
+0

但是'AccountContainer'在语义上代表了一个值吗?它应该是一个结构? – Servy

+0

@Servy这是一个很好的问题。如果改变'Money'的例子是一个经常执行的操作,那么'AccountContainer'可能会作为一个实体更好地服务(按照DDD的说法,就是这样)。我的直觉是,所展示的是更大范围的更小的切割,其中甚至可能有实体与价值数据的功能分解的更好机会。 –