C# 遍历类字段并打印它们

C# 遍历类字段并打印它们,c#,C#,例如,如果我有一门课 public class User{ public int Id { get; set; } public int Reputation { get; set; } public string DisplayName { get; set; } public DateTime LastAccessDate { get; set; } public Date

例如,如果我有一门课

public class User{
            public int Id { get; set; }
            public int Reputation { get; set; }
            public string DisplayName { get; set; }
            public DateTime LastAccessDate { get; set; }
            public DateTime CreationDate { get; set; }
            public string WebSiteUrl { get; set; }
            public int Views { get; set; }
            public int Age { get; set; }
            public int UpVotes { get; set; }
            public int downVotes { get; set; }
            public string Location { get; set; }
            public string AboutMe { get; set; }
    }
我想动态地迭代这些字段,例如,迭代到某个方法,该方法将检查传递的对象,然后返回给调用者它的字段


这可能吗?

它们不是字段,而是属性。您可以使用反射来列出它们:

User user = ...
foreach(PropertyInfo prop in typeof(User).GetProperties())
{
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(user, null));
}

遗憾的是,Google中“C#迭代类字段”的第一个结果实际上是关于迭代属性的问题