在 foreach 循环中更改对象值? [英] Changing objects value in foreach loop?
问题描述
在一个地方,我使用了字符串列表,在这种情况下,我可以按照下面给出的代码更改字符串的值,
In one place i am using the list of string in that case the i am able to change the value of the string as code given below,
foreach(string item in itemlist.ToList())
{
item = someValue; //I am able to do this
}
但是对于类的对象,我无法更改对象的成员值,代码如下,
But for object of class i am not able to alter the members value of the object the code is as below,
public class StudentDTO
{
string name;
int rollNo;
}
studentDTOList=GetDataFromDatabase();
foreach(StudentDTO student in studentDTOList.ToList())
{
student = ChangeName(student); //Not working
}
private StudentDTO ChangeName(StudentDTO studentDTO)
{
studentDTO.name = SomeName;
return studentDTO;
}
错误是:不能赋值,因为它是迭代变量
Error is : Can not assign because it's iteration variable
推荐答案
您不能更改 foreach 循环的迭代变量,但可以更改迭代变量的成员.因此将 ChangeName
方法更改为
You cannot change the iteration variable of a foreach-loop, but you can change members of the iteration variable. Therefore change the ChangeName
method to
private void ChangeName(StudentDTO studentDTO)
{
studentDTO.name = SomeName;
}
注意 studentDTO
是一个引用类型.因此,无需返回更改后的学生.ChangeName
方法得到的不是学生的副本,而是对唯一学生对象的引用.迭代变量和 studentDTOList
都引用了与方法的 studentDTO
参数相同的学生对象.
Note that studentDTO
is a reference type. Therefore there is no need to return the changed student. What the ChangeName
method gets, is not a copy of the student but a reference to the unique student object. The iteration variable and the studentDTOList
both reference the same student object as does the studentDTO
parameter of the method.
并将循环更改为
foreach(StudentDTO student in studentDTOList)
{
ChangeName(student);
}
然而,像 ChangeName
这样的方法并不常见.走的路是将字段封装在一个属性中
However, methods like ChangeName
are unusual. The way to go is to encapsulate the field in a property
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
然后您可以将循环更改为
You can then change the loop to
foreach(StudentDTO student in studentDTOList)
{
student.Name = SomeName;
}
<小时>
编辑
在评论中您说您必须更改许多字段.在这种情况下,可以使用一个方法 UpdateStudent
来完成所有更改;但是我仍然会保留这些属性.
In a comment you say that you have to change many fields. In that case it would be okay to have a method UpdateStudent
that would do all the changes; however I still would keep the properties.
如果属性中除了传递值之外没有其他逻辑,您可以将它们替换为方便的自动实现的属性.
If there is no additional logic in the properties besides passing through a value, you can replace them by the handy auto-implemented properties.
public string Name { get; set; }
在这种情况下,您必须删除字段 name
.
In that case you would have to drop the field name
.
这篇关于在 foreach 循环中更改对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!