1

我正在分析 C# 应用程序并遇到以下情况。如果有人能解释这种行为,我将不胜感激。

我有以下原始 C# 代码:

public class Person
{
    public string firstName;
    public string lastName;
}

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new List<Person>();

        people.Add(new Person{firstName = "John", lastName = "Smith"});
        people.Add(new Person{firstName = "Jim", lastName = "Johnson"});
        people.Add(new Person{firstName = "Sue", lastName = "Rabon"});

        foreach (Person p in people)
            Console.WriteLine(p.firstName + " " + p.lastName);
    }
}

C# 性能分析器显示上述代码如下:

public class Person
{
    public string firstName;
    public string lastName;
}

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new List<Person>();

        people.Add(new Person{firstName = "John", lastName = "Smith"});
        people.Add(new Person{firstName = "Jim", lastName = "Johnson"});
        people.Add(new Person{firstName = "Sue", lastName = "Rabon"});

        foreach (Person p in people)
        foreach (Person p in people)
        foreach (Person p in people)
        foreach (Person p in people)
        foreach (Person p in people)
            Console.WriteLine(p.firstName + " " + p.lastName);
    }
}

重复 foreach 循环。为什么会这样?如果我使用代码反编译器,那么它类似于原始源代码。

4

0 回答 0