为什么我不能直接在C#中编辑列表成员 [英] Why can't I edit a List member directly in C#

查看:64
本文介绍了为什么我不能直接在C#中编辑列表成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个声明为public class DatumSet : List<datum>的类,其中

I have a class declared as public class DatumSet : List<datum>, where

public struct datum {
    public UInt32[] chan;
    public UInt64 sample_number;
    public float time;
    public UInt32 source_sector;
}

我想遍历列表并进行一些更改.为什么这不起作用

I want to iterate through the List and make some changes. Why does this NOT work

        for (int i = 0; i < this.Count; i++) {
            this[i].sample_number = startSample;
            this[i].time = (float)startSample / _sample_rate;
            startSample++;
        }

但这确实有用

        for (int i = 0; i < this.Count; i++) {
            datum d = this[i];
            d.sample_number = sampleNumber;
            d.time = (float)sampleNumber / _sample_rate;
            sampleNumber++;
        }

我得到了错误:

无法修改'System.Collections.Generic.List.this [int]'的返回值,因为它不是变量

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

推荐答案

您遇到了问题,因为您使用的是结构而不是类.

You're having problems because you are using a struct rather than a class.

从集合中检索结构时,将创建一个副本.您的第一组代码给您一个错误,因为它检测到您正在做您可能不想做的事情.实际上,您实际上是在编辑结构的副本,而不是集合中的副本.

When you retrieve a struct from a collection, a copy is made. Your first set of code gives you an error because it detects you're doing something you may not mean to do. You'd actually be editing a copy of the struct rather than the copy in the collection.

第二个不会产生错误,因为您在编辑之前已将副本从集合中明确拉出.该代码可以编译,但不会修改集合中的任何结构,因此不会为您提供期望的结果.

The second doesn't produce an error because you explicitly pull the copy out of the collection before editing. This code may compile, but won't modify any of the structs in the collection and thus won't give you the results that you're expecting.

这篇关于为什么我不能直接在C#中编辑列表成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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