gpt4 book ai didi

c# - 无法修改列表中的结构?

转载 作者:可可西里 更新时间:2023-11-01 08:54:45 26 4
gpt4 key购买 nike

我想更改列表中的货币值,但总是收到错误消息:

Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable

怎么了?如何更改值?

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;

最佳答案

您已将 AccountContainer 声明为 struct。所以

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

创建 AccountContainer 的新实例并将该实例的副本添加到列表中;和

AccountList[0].Money = 547885;

检索列表中第一项的副本,更改副本的 Money 字段并丢弃副本 - 列表中的第一项保持不变。由于这显然不是您想要的,因此编译器会警告您。

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

关于c# - 无法修改列表中的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679033/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com