无法修改列表中的struct?
我想更改列表中的货币值,但我总是收到错误消息:
无法修改’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 AccountList = new List(); AccountList.Add(new AccountContainer("Michael", 54, 3, 512913)); AccountList[0].Money = 547885;
您已将AccountContainer
声明为struct
。 所以
AccountList.Add(new AccountContainer("Michael", 54, 3, 512913));
创建一个新的AccountContainer
实例,并将该实例的副本添加到列表中; 和
AccountList[0].Money = 547885;
检索列表中第一项的副本,更改副本的Money
字段并丢弃副本 – 列表中的第一项保持不变。 由于这显然不是您的意图,编译器会向您发出警告。
解决方案:不要创建可变struct
。 创建一个不可变的struct
(即,在创建之后无法更改的struct
)或创建一个class
。
你正在使用一个邪恶的可变结构。
把它改成一个类,一切都会正常工作。
以下是我将如何为您的场景解决它(使用不可变的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 AccountList = new List (); AccountList.Add(new AccountContainer("Michael", 54, 3, 512913)); AccountList[0] = new AccountContainer( AccountList[0].Name, AccountList[0].Age, AccountList[0].Children, 547885);
可能不推荐,但它解决了这个问题:
AccountList.RemoveAt(0); AccountList.Add(new AccountContainer("Michael", 54, 3, 547885));