【问题标题】:Why struct properties cannot be changed if they are in a list? [duplicate]如果结构属性在列表中,为什么不能更改它们? [复制]
【发布时间】:2019-11-29 11:16:34
【问题描述】:

请考虑以下代码:

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'"
        }
    }
}

所以我的问题是:为什么在迭代结构列表时不能分配结构属性? 请注意,即使像这样使用简单的 for 进行迭代:

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

我仍然收到编译时错误...

【问题讨论】:

标签: c# list loops compiler-errors value-type


【解决方案1】:

您不能使用 foreach 修改您正在迭代的集合。

您应该使用for 循环,它允许:

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

你可以参考这个问题:Why can't we assign a foreach iteration variable, whereas we can completely modify it with an accessor?

【讨论】:

  • 请检查更新,即使在 for 循环中我仍然无法更改属性
  • 抱歉,这里有一个不同的问题。代码中的任何地方都不会修改集合。只有当list 是一个数组时,您的代码才会编译。
猜你喜欢
  • 1970-01-01
  • 2019-05-07
  • 2020-04-17
  • 2018-10-12
  • 2015-12-09
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2019-05-31
相关资源
最近更新 更多