Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么结构属性在列表中时不能更改? 请考虑以下代码: public class Program { public struct A { public int Prop {get;set;} } public static void Main() { var obj = new A(); obj.Prop = 10; var list = new List<A>(){obj}; foreach(var l in list) { l.Prop = 20; //here I'm getting compile time error "Cannot modify members of 'l' because it is a 'foreach iteration variable'" } } } 公共类程序{ 公共结构A { 公共int属性{get;set;} } 公共静态void Main() { var obj=新的A(); 对象属性=10; var list=new list(){obj}; foreach(列表中的变量l){ l、 Prop=20;//这里出现编译时错误“无法修改'l'的成员,因为它是'foreach迭代变量'” } } }_C#_List_Loops_Compiler Errors_Value Type - Fatal编程技术网

C# 为什么结构属性在列表中时不能更改? 请考虑以下代码: public class Program { public struct A { public int Prop {get;set;} } public static void Main() { var obj = new A(); obj.Prop = 10; var list = new List<A>(){obj}; foreach(var l in list) { l.Prop = 20; //here I'm getting compile time error "Cannot modify members of 'l' because it is a 'foreach iteration variable'" } } } 公共类程序{ 公共结构A { 公共int属性{get;set;} } 公共静态void Main() { var obj=新的A(); 对象属性=10; var list=new list(){obj}; foreach(列表中的变量l){ l、 Prop=20;//这里出现编译时错误“无法修改'l'的成员,因为它是'foreach迭代变量'” } } }

C# 为什么结构属性在列表中时不能更改? 请考虑以下代码: public class Program { public struct A { public int Prop {get;set;} } public static void Main() { var obj = new A(); obj.Prop = 10; var list = new List<A>(){obj}; foreach(var l in list) { l.Prop = 20; //here I'm getting compile time error "Cannot modify members of 'l' because it is a 'foreach iteration variable'" } } } 公共类程序{ 公共结构A { 公共int属性{get;set;} } 公共静态void Main() { var obj=新的A(); 对象属性=10; var list=new list(){obj}; foreach(列表中的变量l){ l、 Prop=20;//这里出现编译时错误“无法修改'l'的成员,因为它是'foreach迭代变量'” } } },c#,list,loops,compiler-errors,value-type,C#,List,Loops,Compiler Errors,Value Type,所以我的问题是:为什么在遍历结构列表时不能分配结构属性? 请注意,即使使用simple for进行迭代,如下所示: for (int i=0; i<list.Count(); ++i) list[i].Prop = 20; for(int i=0;i您不能修改使用foreach进行迭代的集合 相反,您应该为循环使用,这允许: for(int i = 0; i < list.Length; i++) { list[i].Prop = 200; } for(int i=

所以我的问题是:为什么在遍历结构列表时不能分配结构属性? 请注意,即使使用simple for进行迭代,如下所示:

for (int i=0; i<list.Count(); ++i)
    list[i].Prop  = 20;

for(int i=0;i您不能修改使用
foreach进行迭代的集合

相反,您应该为
循环使用
,这允许:

for(int i = 0; i < list.Length; i++)
{
  list[i].Prop = 200;
}
for(int i=0;i

您可以参考此问题:

请签出更新,即使在for loop中,我仍然无法对属性进行更改抱歉,这里有一个不同的问题。集合在代码中的任何位置都没有修改。只有当
list
是数组时,您的代码才会编译。关于for loop,您需要创建一个st的副本参见: