在C#中为迭代变量赋值?

Bri*_*rij 2 c# iteration foreach

我在C#中使用了以下代码foreach.在一个循环中,我正在修改List<T>一个string数组,而在另一个循环中,

我们不能直接为迭代变量赋值或null,但是我们可以修改它的属性,并且修改会反映在Listfinally中.

所以这基本上意味着迭代变量是对列表中元素的引用,那么为什么我们不能直接为它赋值?

class Program
{
    public static void Main(string[] args)
    {
        List<Student> lstStudents = Student.GetStudents();

        foreach (Student st in lstStudents)
        {
            // st is modified and the modification shows in the lstStudents
            st.RollNo = st.RollNo + 1;

            // not allowed
            st = null;
        }

        string[] names = new string[] { "me", "you", "us" };

        foreach (string str in names)
        {
            // modifying str is not allowed
            str = str + "abc";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

学生班:

class Student
{
    public int RollNo { get; set; }
    public string Name { get; set; }

    public static List<Student> GetStudents()
    {
        List<Student> lstStudents = new List<Student>();

        lstStudents.Add(new Student() { RollNo = 1, Name = "Me" });
        lstStudents.Add(new Student() { RollNo = 2, Name = "You" });
        lstStudents.Add(new Student() { RollNo = 3, Name = "Us" });

        return lstStudents;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 7

在一个迭代变量foreach不是一个"参考列表中的元素" -它仅仅是从值.Current {get;}在迭代器通过获得实现GetEnumerator()-最常见的通过IEnumerator[<T>],但并不总是-确实是一个List<T>它是一个List<T>.Enumerator值.在一般情况下,分配给迭代器变量没有"意义".考虑:

IEnumerable<int> RandomSequence(int count) {
    var rand = new Random();
    while(count-->0) yield return rand.Next();
}
Run Code Online (Sandbox Code Playgroud)

这将同样适用foreach- 分配给它的意义是什么?

因此,foreach没有提供分配给迭代器变量的工具.