遍历类字段并打印
问题描述:
例如,如果我有一个像这样的班级
If I have for example one class like
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; }
}
我想动态地遍历这些字段,例如,某种方法将检查传递的对象,并将其返回给调用方其字段.
And I want to iterate through these fields dynamicly, for example to some method which will inspect passed object and it will return to caller its fields.
这可能吗?
答
它们不是字段,而是属性.您可以使用反射将其列出:
They're not fields, they're properties. You can use reflection to list them:
User user = ...
foreach(PropertyInfo prop in typeof(User).GetProperties())
{
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(user, null));
}