不能修改结构列表中? [英] Cannot modify struct in a list?
问题描述
我想在我的名单改变货币价值,但我总是得到一个错误信息:
不能修改的返回值System.Collections.Generic.List.this [INT],因为它不是一个变量
块引用>
什么是错的? ?我怎样才能更改值
结构AccountContainer
{
公共字符串名称;
公众诠释年龄;
公众诠释儿童;
公众诠释钱;
公共AccountContainer(字符串名称,诠释年龄,孩子们诠释,诠释钱)
:这()
{
this.Name =名称;
this.Age =年龄;
this.Children =儿童;
this.Money =钱;
}
}
名单,LT; AccountContainer>为accountList =新的List< AccountContainer>();
AccountList.Add(新AccountContainer(迈克尔,54,3,512913));
为accountList [0] = .Money 547885;
解决方案您已经声明
AccountContainer
为结构
。因此,AccountList.Add(新AccountContainer(迈克尔,54,3,512913));
创建
AccountContainer
的新实例,并增加了该实例清单复印件;以及为accountList [0] = .Money 547885;
检索列表中的第一个项目的副本,改变了
货币
复制领域,并放弃副本&ndash的;在列表中的第一项将保持不变。由于这显然不是你的本意,编译器警告您关于这个
的解决方法:的不要创建可变
结构
秒。创建一个不可变结构
(即,一个不能在创建后更改),或创建一个类
。I want to change the money value in my list, but I always get an error message:
Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable
What is wrong? How can I change the value?
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;
解决方案You have declared
AccountContainer
as astruct
. SoAccountList.Add(new AccountContainer("Michael", 54, 3, 512913));
creates a new instance of
AccountContainer
and adds a copy of that instance to the list; andAccountList[0].Money = 547885;
retrieves a copy of the first item in the list, changes the
Money
field of the copy and discards the copy – the first item in the list remains unchanged. Since this is clearly not what you intended, the compiler warns you about this.Solution: Do not create mutable
struct
s. Create an immutablestruct
(i.e., one that cannot be changed after it has been created) or create aclass
.这篇关于不能修改结构列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!