今天做項目遇到個需求,獲取這個對象里的所有的方法和屬性,下面我就介紹一下如何遍歷類的所有屬性和方法。
首先我定義了一個 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
