迭代类字段并打印它们

Bob*_*ock 21 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 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; }
    }
Run Code Online (Sandbox Code Playgroud)

我想动态地遍历这些字段,例如检查传递对象的某个方法,它将返回调用者的字段.

这可能吗 ?

Tho*_*que 54

他们不是田地,他们是财产.您可以使用反射列出它们:

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