On the usage of foreach in C #

Source: Internet
Author: User

Introduction

I did my teacher's website yesterday. To add modifications to some objects delete processing. Nothing else, there was something wrong with the deletion.

Because you are removing an element from a collection of classes. This will traverse the entire collection, and foreach is the new gadget for traversal. It's a natural use. So the code looks like this:

string temp = name.Text; // 从TextBox中读出数据
foreach (LCourse cou in Data.myCourse) // 在List中遍历
{
if (cou.name == temp) // 判断cou的名字匹配
{
Data.myCourse.Remove(cou); // 匹配的即为要删除的,从列表中去除
break; // 跳出循环
}
}

It's easy to think of this with foreach, and it seems like there's no mistake. But the impression that the note about foreach is only applicable to traversal reads, cannot be modified. The top code was deleted successfully. In this way, the seeds of contradictions are planted in the heart, in the end what is a foreach thing?

Process:

Looked at the MSDN documentation, but the example in the documentation used to iterate through each element, so it didn't help much. Related tests, exceptions, compile errors are of great use.

Process details and summaries:

1. Custom integer array and then iterate through the modifications

foreach(int myint in myArray)
{ myint+=8;}

Error: "Myint" is a "foreach iteration variable" and cannot be assigned a value of G:\TEST\VS ... C#\testforeach\program.cs Testforeach

2. Custom classes, define functions in the class to manipulate private members, and then iterate over the class object and call the function

public class MyClass // 自定义的测试类
{
private int i = 0;
public void change()
{
i = 98;
}
public override string ToString()
{
return i.ToString();
}
}
MyClass[] myTest = new MyClass[10]; // 测试代码片段
foreach (MyClass mc in myTest)
{
mc.change();
Console.WriteLine(mc.ToString());
}

The compilation was passed, but an exception was thrown, Nullrefferenceexception, and the object reference was not set to an instance of the object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.