在结构的列表改变一个元素的值 [英] Changing the value of an element in a list of structs

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

问题描述

我有结构的列表,我想换一个元素。例如:

  MyList.Add(新MYSTRUCT(约翰);
MyList.Add(新MYSTRUCT(彼得);

现在我想改变一个元素:

  MYLIST [1] .Name点=鲍勃

然而,每当我试图做到这一点我得到以下错误:


  

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


如果我用类的列表,不会发生问题。

我想答案与结构是一个值类型的事情。

所以,如果我有结构的名单,我应该把他们当作的只读的?如果我需要改变的元素列表中的话,我应该使用类而不是结构?


解决方案

  MYLIST [1] =新MYSTRUCT(鲍勃);

在C#结构应该总是被设计为不可变的(即没有办法改变他们的内部状态,一旦被创建)。

在你的情况,你想要做的是更换指定数组索引整个结构,而不是试图改变只是一个单一的属性或字段。

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:

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

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天全站免登陆