You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何使用for循环替代foreach遍历List<>访问对象元素并打印

错误原因
  • 你已经通过People[i]拿到了当前索引对应的Person对象,取出的name是完整的姓名字符串,此时对name加[i]会读取字符串的第i位字符,因此只会输出单个字符,而非完整姓名。
  • age是int值类型,本身不支持索引器[]访问,因此代码会直接抛出编译错误。
正确实现逻辑

for循环中变量i是List集合的索引,只需要通过i取出对应的Person对象后,直接输出它的Name、Age属性即可,不需要对属性再加索引:

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循环
            for(int i=0; i<People.Count; i++)
            {
                var currentPerson = People[i];
                Console.WriteLine(currentPerson.Name + " " + currentPerson.Age);
            } 
        }
    }
}

内容的提问来源于stack exchange,提问作者bunnap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:30:02