C# 遍历类的所有属性和方法

今天做项目遇到个需求,获取这个对象里的所有的方法和属性,下面我就介绍一下如何遍历类的所有属性和方法。

首先我定义了一个 User 类用做演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class User
{
 
    private int userId = 1;
 
    public int UserId
    {
        get { return userId; }
        set { userId = value; }
    }
 
    private string username = "charles";
 
    public string Username
    {
        get { return username; }
        set { username = value; }
    }
 
    private string address = "Beijing";
 
    public string Address
    {
        get { return address; }
        set { address = value; }
    }
 
    private string email = "master@weilog.net";
 
    public string Email
    {
        get { return email; }
        set { email = value; }
    }
 
    private string phone = "13888888888";
 
    public string Phone
    {
        get { return phone; }
        set { phone = value; }
    }
 
 
    public string ToJson()
    {
        return "{\"UserId\":\"" + userId + "\",\"Username\":\"" + username + "\",\"Address\":\"" + address + "\",\"Email\":\"" + email + "\",\"Phone\":\"" + phone + "\"}";
    }
}

1、通过实例化属性和方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Reflection;
 
class Program {
 
    public static int Main (string[] args) {
 
        // 实例化对象。
        User user = new User ();
        // 打印 User 的属性。
        Console.Write ("\nUser.UserId = " + user.UserId);
        Console.Write ("\nUser.Username = " + user.Username);
        Console.Write ("\nUser.Address = " + user.Address);
        Console.Write ("\nUser.Email = " + user.Email);
        Console.Write ("\nUser.Phone = " + user.Phone);
        Console.Write ("\nUser.ToJson = " + user.ToJson ());
        Console.ReadLine ();
    }
}

启动程序输出结果如下:

1
2
3
4
5
6
User.UserId = 1
User.Username = charles
User.Address = Beijing
User.Email = master @weilog.net
User.Phone = 13888888888
User.ToJson = { "UserId": "1", "Username": "charles", "Address": "Beijing", "Email": "master@weilog.net", "Phone": "13888888888" }

2、通过反射即可遍历属性

需要注意的是项目中需要使用 System.Reflection 这个命名空间。

Type 类的常用方法:

1
2
3
4
5
6
7
8
// 获取所有方法
MethodInfo[] methods = type.GetMethods ();
 
// 获取所有成员
MemberInfo[] members = type.GetMembers ();
 
// 获取所有属性
PropertyInfo[] properties = type.GetProperties ();

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Program {
     
    static void Main (string[] args) {
 
        Type type = typeof (User);
        object obj = Activator.CreateInstance (type);
        // 获取所有方法。
        MethodInfo[] methods = type.GetMethods ();
        // 遍历方法打印到控制台。
        foreach (PropertyInfo method in methods) {
            Console.WriteLine (method.Name);
        }
 
        // 获取所有成员。
        MemberInfo[] members = type.GetMembers ();
        // 遍历成员打印到控制台。
        foreach (PropertyInfo members in members) {
            Console.WriteLine (members.Name);
        }
        // 获取所有属性。
        PropertyInfo[] properties = type.GetProperties ();
 
        // 遍历属性打印到控制台。
        foreach (PropertyInfo prop in properties) {
            Console.WriteLine (prop.Name);
        }
        Console.ReadLine ();
 
    }
}

另外我们也可以通过反射实例化类:

1
object obj = Activator.CreateInstance(type);

官方参考:http://msdn.microsoft.com/zh-cn/library/system.reflection.propertyinfo.attributes

posted @   Charles Zhang  阅读(20154)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示