C# 遍历类的所有属性和方法
今天做项目遇到个需求,获取这个对象里的所有的方法和属性,下面我就介绍一下如何遍历类的所有属性和方法。
首先我定义了一个 User 类用做演示:
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、通过实例化属性和方法
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 (); } }
启动程序输出结果如下:
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 类的常用方法:
// 获取所有方法 MethodInfo[] methods = type.GetMethods (); // 获取所有成员 MemberInfo[] members = type.GetMembers (); // 获取所有属性 PropertyInfo[] properties = type.GetProperties ();
完整代码:
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 (); } }
另外我们也可以通过反射实例化类:
object obj = Activator.CreateInstance(type);
官方参考:http://msdn.microsoft.com/zh-cn/library/system.reflection.propertyinfo.attributes