c# - 直接修改 List<T> 元素

标签 c# .net

我有这个结构:

struct Map
{
    public int Size;

    public Map ( int size )
    {
        this.Size = size;
    }

    public override string ToString ( )
    {
        return String.Format ( "Size: {0}", this.Size );
    }
}

当使用数组时,它有效:

Map [ ] arr = new Map [ 4 ] {
    new Map(10),
    new Map(20),
    new Map(30),
    new Map(40)};

arr [ 2 ].Size = 0;

但是当使用 List 时,它不编译:

List<Map> list = new List<Map> ( ) {
    new Map(10),
    new Map(20),
    new Map(30),
    new Map(40)};

list [ 2 ].Size = 0;

为什么?

最佳答案

C# 编译器会给出以下错误:

Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable

原因是结构是值类型,所以当您访问列表元素时,您实际上将访问列表索引器返回的元素的中间副本。

来自 MSDN :

Error Message

Cannot modify the return value of 'expression' because it is not a variable

An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.

To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.

解决方案:

  1. 使用数组。这使您可以直接访问元素(您没有访问副本)
  2. 当您将 Map 设为类时,您仍然可以使用 List 来存储您的元素。然后,您将获得对 Map 对象的引用而不是中间副本,并且您将能够修改该对象。
  3. 如果您无法将 Map 从结构更改为类,则必须将列表项保存在临时变量中:

List<Map> list = new List<Map>() { 
    new Map(10), 
    new Map(20), 
    new Map(30), 
    new Map(40)
};

Map map = list[2];
map.Size = 42;
list[2] = map;

关于c# - 直接修改 List<T> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/414981/

相关文章:

c# - 防止在设计时调整高度控件的大小

c# - 如何使[示例]扩展方法更加通用/实用/高效?

c# - .Net/C# 中远程启动和关闭 Azure 服务器

c# - 删除字符串中的空格

c# - 如何对 ToolStripDropDownButton 的 DropDownMenu 上的鼠标滚轮使用react?

c# - 快速视频显示 WPF

c# - 尝试将文件从 UWP 应用程序上传到 Flask restful web api,失败

c# - 我们可以继承单例类吗?

c# - 我应该在哪里放置我的数据库连接字符串以及如何处理连接池?

c# - 如何将动态sql列读入C#