對象轉化成鍵值對

控制檯程序:

class Program
    {
        static void Main(string[] args)
        {
            User u = new User();
            u.name = "ahbool";
            u.gender = "男";
            u.age = "1";

            Console.WriteLine(GetProperties(u));

        }

        public static string GetProperties<T>(T t)
        {
            string tStr = string.Empty;
            if (t == null)
            {
                return tStr;
            }
            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            if (properties.Length <= 0)
            {
                return tStr;
            }
            foreach (System.Reflection.PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(t, null);
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    tStr += string.Format("{0}:{1},", name, value);
                }
                else
                {
                    GetProperties(value);
                }
            }
            return tStr;
        }

    }

    public class User
    {
        public string name { get; set; }
        public string gender { get; set; }
        public string age { get; set; }
    }

輸出效果:

name:ahbool,gender:男,age:1,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章