c# - 无法在通用集合中更改结构的成员值

标签 c# .net struct generic-list generic-collections

想象一下这个结构:

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

和下面的代码:

        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";

当我想更改 Property 的值时,出现以下错误:

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

虽然,当我尝试在数组(例如 Person[])中更改它时,它没有任何错误地工作。使用通用集合时,我的代码是否有任何问题?

最佳答案

当您通过 List[] 索引器返回 struct 时,它会返回条目的副本。因此,如果您在那里分配了 FirstName,它就会被丢弃。因此编译器错误。

要么重写你的 Person 成为一个引用类型 class,要么做一个完整的重新分配:

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

一般来说,可变结构会带来诸如此类的问题,这些问题可能会在以后引起麻烦。除非你有充分的理由使用它们,否则你应该强烈考虑更改你的 Person 类型。

Why are mutable structs “evil”?

关于c# - 无法在通用集合中更改结构的成员值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14945118/

相关文章:

c - "Error: parameter name omitted"并将输入文件作为参数传递

c# - 入口点不能用 'async' 修饰符标记

c# - DataBinding() 不适用于 Distinct()( Entity Framework )

c# - 如何不使用 UserControl.dispose()

.net - 正则表达式替换帮助

.net - 托管 C++ 方法命名

c# - 覆盖 XmlSerialization 的类名

c# - Microsoft 服务管理器控制台 API?

swift - 如何正确打印结构?

c# - 为什么在结构中使用 LINQ 时必须复制 "this"(如果我这样做可以)?