2013-03-14 14 views
4

我在使用结构时遇到问题。如何解决此问题:Struct In Collection未更改

我有这样的结构:

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 

为什么我我得到这个错误以及如何解决它?

+1

为什么你使用'struct'? – 2013-03-14 11:38:10

+3

在我看来,这个问题已经涵盖:http://stackoverflow.com/questions/1067340/c-sharp-modifying-structs-in-a-listt – 2013-03-14 11:41:24

回答

4

结构通常是可变的,也就是说你可以直接修改其成员的值。

根据这一website

但是,如果一个结构是一个集合类使用,就像一个列表,你不能修改它的成员。通过索引到集合中引用项目将返回一个无法修改的结构副本。要更改列表中的项目,您需要创建一个新的结构实例。

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 
+0

你*可以*修改副本(如果你存储在一个变量),但它是被修改的* copy *,而不是List中的原始结构。 – 2013-03-14 11:52:25