【问题标题】:How to solve this:Struct In Collection not changed [duplicate]如何解决这个问题:集合中的结构没有改变[重复]
【发布时间】:2013-03-02 17:39:18
【问题描述】:

我在使用结构时遇到问题。

我有这个结构:

struct MyStruct
{
  public int x;
  public int y;

  public MyStruct(int x,int y)
  {
    this.x = x;
    this.y = y;
  }
}

当我尝试将此结构添加到这样的列表中时:

List<MyStruct> myList = new List<MyStruct>();

// Create a few instances of struct and add to list
myList.Add(new MyStruct(1, 2));
myList.Add(new MyStruct(3, 4));
myList[1].x = 1;//<=====Compile-time error!

我收到此错误:

Compile-time error: Can't modify '...' because it's not a variable

为什么会出现此错误以及如何解决?

【问题讨论】:

标签: c# .net list struct


【解决方案1】:

结构通常是可变的,即您可以直接修改其成员的值。

据此website

但是,如果在集合类中使用结构,例如 List,则不能修改其成员。通过对集合进行索引来引用该项目会返回该结构的副本,您无法对其进行修改。要更改列表中的项目,您需要创建该结构的新实例。

    List<MyStruct> myList = new List<MyStruct>();

 // Create a few instances of struct and add to list
myList.Add(new MyStruct(1, 2));
myList.Add(new MyStruct(3, 4));
myList[1].x = 1;//<=====Compile-time error!

 // Do this instead
 myList[1] = new MyStruct(1,myList[1].y);

如果将结构存储在数组中,则可以更改结构成员之一的值。

 MyStruct[] arr = new MyStruct[2];
 arr[0] = new MyStruct(1, 1);
 arr[0].x= 5.0;  // OK

【讨论】:

  • 可以修改副本(如果将其存储在变量中),但修改的是 copy,而不是原始结构列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多