Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

c# - Cannot modify struct in a list?

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...