using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { StringBuilder builder = new StringBuilder(); User user = new User("abc","123456"); Person p = new Person(); p.Code = "B0531"; p.User = user; //Console.WriteLine(Get<User>(ref builder,user)); //Console.WriteLine(); Get<Person>(ref builder, p); Console.WriteLine(builder.ToString()); Console.Read(); } private static void Get<T>(ref StringBuilder builder,T obj) //where T:new() { //T type = new T(); //PropertyInfo[] properties = type.GetType().GetProperties(); if (obj == null) { return; } PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (properties.Length == 0) { return; } //builder.AppendFormat("\"{0}\":{", obj.GetType().Name); builder.Append("\"" + obj.GetType().Name + "\":{"); for (int i = 0; i < properties.Length;i++ ) { if(properties[i].PropertyType.IsValueType||properties[i].PropertyType.Name.StartsWith("String")){ builder.AppendFormat("\"{0}\":\"{1}\"", properties[i].Name, properties[i].GetValue(obj, null)); } else{ Get(ref builder,properties[i].GetGetMethod().Invoke(obj,null)); } if(i<properties.Length-1){ builder.Append(","); } } builder.Append("}"); //return builder.ToString(); } } public class Person { private string _code; private User _user; public string Code { get { return this._code; } set { this._code = value; } } public User User { get { return this._user; } set { this._user = value; } } } public class User { private string _name; private string _secret; public string Name { get { return this._name; } set { this._name = value; } } public string Secret { get { return this._secret; } set { this._secret = value; } } public User() { } public User(string name,string secret) { this._name = name; this._secret = secret; } } }
实际上,这段代码的关键是:PropertyInfo.GetGetMethod()方法
PropertyInfo.GetGetMethod返回表示此属性的get访问器的MethodInfo