不能改变结构的成员里面泛型集合的值 [英] Can't change struct's members value inside generic collections

查看:175
本文介绍了不能改变结构的成员里面泛型集合的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下结构

        struct Person
        {
             public string FirstName { get; set; }
             public string LastName { get; set; }
        }

和以下code:

        var list = new List<Person>();
        list.Add(new Person { FirstName = "F1", LastName = "L1" });
        list.Add(new Person { FirstName = "F2", LastName = "L2" });
        list.Add(new Person { FirstName = "F3", LastName = "L3" });

        // Can't modify the expression because it's not a variable
        list[1].FirstName = "F22";

当我想换属性的值,它给了我下面的错误:

When I want to change Property's value it gives me the following error:

Can't modify the expression because it's not a variable

虽然,当我试图数组内改变,如人[] 它时,使用的工作没有任何error.Is那里与我的code任何问题与泛型集合?

While, when I tried to change it inside an array such as Person[] it worked without any error.Is there any problem with my code when using with generic collections?

推荐答案

当您返回结构通过列表[] 索引,它返回条目的复制的。因此,如果您分配了名字在那里,它只是被扔掉。因此,编译器错误。

When you return the struct via the List[] indexer, it returns a copy of the entry. So if you assigned the FirstName there, it would just be thrown away. Hence the compiler error.

要么重写你的来引用类型,或做一个完整的重新分配:

Either rewrite your Person to be a reference type class, or do a full reassignment:

Person person = list[1];
person.FirstName = "F22";
list[1] = person;

一般来说,可变结构带来的问题,如这些,可引起头痛的道路。除非你有一个很好的理由来使用它们,你应该认真考虑改变你的键入

为什么是可变的结构邪?

这篇关于不能改变结构的成员里面泛型集合的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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