直接修改清单< T>分子 [英] Directly modifying List<T> elements

查看:188
本文介绍了直接修改清单< T>分子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构:

struct Map
{
    public int Size;

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

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

在使用数组,它的工作原理:

When using array, it works:

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

arr [ 2 ].Size = 0;

但在使用列表时,它并不能编译:

But when using List, it doesn't compile:

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

list [ 2 ].Size = 0;

为什么?

推荐答案

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

The C# compiler will give you the following error:

不能修改System.Collections.Generic.List.this [INT]'的返回值,因为它不是一个变量

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

原因是,结构是值类型,所以当你访问一个列表元素,你实际上将获得已返回列表索引元素的中间副本。

The reason is that structs are value types so when you access a list element you will in fact access an intermediate copy of the element which has been returned by the indexer of the list.

MSDN

错误信息

不能修改的返回值   '前pression',因为它不是一个   变量

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

这是试图修改值   键入是一个结果   中间EX pression。由于   值不坚持,该值将   保持不变。

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.

要解决此错误,存储   的EX pression在结果   中间值,或使用一个参考   键入中间EX pression。

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. 当你映射一个类,你仍然可以使用一个列表来存储你的元素。然后你会得到一个参照地图对象,而不是中间副本,你将能够修改的对象。
  3. 如果您不能从结构改变映射到一个类,你必须保存在临时变量列表项:

&NBSP;

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;

这篇关于直接修改清单&LT; T&GT;分子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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