更改结构列表中元素的值 [英] Changing the value of an element in a list of structs

查看:22
本文介绍了更改结构列表中元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构列表,我想更改一个元素.例如:

I have a list of structs and I want to change one element. For example :

MyList.Add(new MyStruct("john");
MyList.Add(new MyStruct("peter");

现在我想改变一个元素:

Now I want to change one element:

MyList[1].Name = "bob"

但是,每当我尝试这样做时,都会出现以下错误:

However, whenever I try and do this I get 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

如果我使用类列表,则不会出现问题.

If I use a list of classes, the problem doesn't occur.

我想答案与结构是一种值类型有关.

I guess the answer has to do with structs being a value type.

那么,如果我有一个结构列表,我应该将它们视为只读吗?如果我需要更改列表中的元素,那么我应该使用类而不是结构吗?

So, if I have a list of structs should I treat them as read-only? If I need to change elements in a list then I should use classes and not structs?

推荐答案

MyList[1] = new MyStruct("bob");

C# 中的结构应该几乎总是被设计成不可变的(也就是说,一旦它们被创建,就无法改变它们的内部状态).

structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).

在您的情况下,您想要做的是替换指定数组索引中的整个结构,而不是尝试仅更改单个属性或字段.

In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.

这篇关于更改结构列表中元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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