不能修改结构列表中? [英] Cannot modify struct in a list?

查看:109
本文介绍了不能修改结构列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的名单改变货币价值,但我总是得到一个错误信息:




不能修改的返回值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 a struct. So

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

creates a new instance of AccountContainer and adds a copy of that instance to the list; and

AccountList[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 structs. Create an immutable struct (i.e., one that cannot be changed after it has been created) or create a class.

这篇关于不能修改结构列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆