遍历类字段并打印 [英] Iterate through class fields and print them

查看:50
本文介绍了遍历类字段并打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个像这样的班级

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));
}

这篇关于遍历类字段并打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆