C# 传入任意类,得到类的属性值,以list返回

来源:互联网 发布:淘宝服装购买合同范本 编辑:程序博客网 时间:2024/06/06 03:48
  /// <summary>
        /// 得到类的属性值列表。以list方式返回
        /// </summary>
        /// <param name="O"></param>
        /// <returns></returns>
        public static List<string> getValues(object O)
        { 
            List<string> P = new List<string>();


            try
            {
                 
                PropertyInfo[] propertyInfo = O.GetType().GetProperties();
                for (int i = 0; i < propertyInfo.Length; i++)
                {
                    object objectValue = propertyInfo[i].GetGetMethod().Invoke(O, null);
                    if (objectValue == null)
                    {
                        P.Add("''") ;
                        continue;
                    } 
                    if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
                    {
                        P.Add("'" + objectValue.ToString() + "'");
                    }
                    else if (objectValue is string)
                    {
                        P.Add("'" + objectValue.ToString() + "'");
                    }
                    else if(objectValue is Int32 || objectValue is Int64)
                    {
                        P.Add(objectValue.ToString());
                    }
                    //else if (objectValue is IEnumerable)
                    //{
                    //    P.Add(getValues((IEnumerable)objectValue));
                    //}
                    else
                    {
                        P.Add("'" + objectValue.ToString() + "'");
                    }
                    


                }
               
            }
            catch (Exception ex)
            {
                throw ex;
            }


            return P;
        }
0 0
原创粉丝点击