在foreach循环改变对象的价值? [英] Changing objects value in foreach loop?

查看:216
本文介绍了在foreach循环改变对象的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个地方,我用在这种情况下字符串列表中我能够改变下面给出的字符串作为密码的值,

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())
{
      studentDTO=ChangeName(studentDTO); //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 均引用同一个Student对象一样的方法的 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; }
}

您可以然后更改循环

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; }

在这种情况下,你将不得不放弃该领域名称

In that case you would have to drop the field name.

这篇关于在foreach循环改变对象的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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