15

リストの金額を変更したいのですが、常にエラー メッセージが表示されます。

変数ではないため、'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<AccountContainer> AccountList = new List<AccountContainer>();

AccountList.Add(new AccountContainer("Michael", 54, 3, 512913));
AccountList[0].Money = 547885;
4

4 に答える 4

19

として宣言AccountContainerしましたstruct。そう

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

の新しいインスタンスを作成し、AccountContainerそのインスタンスのコピーをリストに追加します。と

AccountList[0].Money = 547885;

リストの最初の項目のコピーを取得し、コピーのMoneyフィールドを変更してコピーを破棄します。リストの最初の項目は変更されません。これは明らかに意図したものではないため、コンパイラはこれについて警告します。

解決策:変更可能な を作成しないでくださいstruct。不変struct(つまり、作成後に変更できないもの) を作成するか、class.

于 2013-05-21T20:39:37.330 に答える
12

邪悪な可変構造体を使用しています。

それをクラスに変更すると、すべてが正常に機能します。

于 2013-05-21T20:38:37.050 に答える
0

あなたのシナリオでそれを解決する方法は次のとおりです(に変更するのではなく、不変structclassメソッドを使用します):

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<AccountContainer> AccountList = new List<AccountContainer>();

AccountList.Add(new AccountContainer("Michael", 54, 3, 512913));
AccountList[0] = new AccountContainer(
    AccountList[0].Name,
    AccountList[0].Age,
    AccountList[0].Children,
    547885);
于 2013-05-21T21:14:20.030 に答える
0

おそらく推奨されませんが、問題は解決します。

AccountList.RemoveAt(0);
AccountList.Add(new AccountContainer("Michael", 54, 3, 547885));
于 2013-05-21T21:09:48.223 に答える