更新结构体在C#中foreach循环 [英] Update Struct in foreach loop in C#

查看:206
本文介绍了更新结构体在C#中foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code(C#):

I have this code (C#):

using System.Collections.Generic;

namespace ConsoleApplication1
{
    public struct Thing
    {
        public string Name;
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Thing> things = new List<Thing>();
            foreach (Thing t in things) //  for each file
            {
                t.Name = "xxx";
            }
        }
    }
}

这将无法编译。
错误是:

It won't compile.
The error is:

Cannot modify members of 't' because it is a 'foreach iteration variable'

如果我修改的事,而不是结构,但是,它编译。

If I change Thing to a class rather than a struct, however, it does compile.

请能有人解释这是怎么回事?

Please can someone explain what's going on?

推荐答案

更​​多或更少的说话是算数的,编译器不会让你改变(部分)在foreach循环的变种。

More or less what it says, the compiler won't let you change (parts of) the looping var in a foreach.

只需使用:

for(int i = 0; i < things.Count; i+= 1) //  for each file
{
    things[i].Name = "xxx";
}

和它的工作原理,当的事是一类,因为那么你的循环var是一个参考,你只更改引用的对象,而不是引用本身。

And it works when Thing is a class because then your looping var is a reference, and you only make changes to the referenced object, not to the reference itself.

这篇关于更新结构体在C#中foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆