C# 使用 for 循环而不是 foreach 从 List<> 访问对象元素

C# accessing element of object from List<> using for loop instead of foreach

试图复习我的 C# 基础。如何打印列表中对象的值?我有一个列表,想打印出姓名和年龄来控制台。

我可以使用 foreach 循环轻松打印出他们的全名和年龄,但我只是好奇如何通过 for 循环来完成这里是我的代码,但我失败了,因为 感谢您的意见和帮助

namespace Rextester
{
    public class Person
    {
        
        public string Name {get;set;}
        public int Age {get; set;}

    }
    public class Program
    {
        public static void Main(string[] args)
        {
            
            
            var People = new List<Person>
            {
                new Person{Name ="mary", Age= 60},
                new Person{Name ="john", Age = 40},
                new Person{Name ="peter", Age= 50},
                new Person{Name ="jane", Age=30}
            };

            foreach(var obj in People)
            {
                Console.WriteLine(obj.Name + obj.Age);
            }
            
            for(int i=0; i<People.Count; i++)
            {
                var name = People[i].Name;
                var age = People[i].Age;
                Console.WriteLine(name[i]); // result is char in each index of string m, o ,t, e  instead of name - mary, john, peter, jane
                Console.WriteLine(age[i]);// error: Cannot apply indexing with [] to an expression of type 'int'
            } 
        }
    }
}

你几乎什么都自己做了:

Console.WriteLine(People[i].Name);
Console.WriteLine(People[i].Age);