Ho questo codice (C#):Aggiornamento Struct in foreach ciclo in 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";
}
}
}
}
Non verrà compilato.
L'errore è:
Cannot modify members of 't' because it is a 'foreach iteration variable'
Se cambio Thing
ad un class
piuttosto che un struct
, tuttavia, si compila.
Per favore qualcuno può spiegare cosa sta succedendo?
domanda correlata http://stackoverflow.com/questions/1538301/c-does-foreach-iterate-by-reference/1538316#1538316 –
Grazie per il collegamento, Brian. –