对象转化成键值对

控制台程序:

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)
        {
            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,

你可能感兴趣的:(C#,.net,键值对)