遍历C#属性的通用方法

  今天在工作中需要将一个类中所有的属性的NAME,以及VALUE添加进一个容器中。一个一个判断添加很慢,突然想到有遍历属性的办法。于是写了一个通用的方法,

代码如下:

   private Dictionary<string, string> GetParaByEntity<T>( T entity ) where T : class
        {
            if ( entity == null )
            {
                return null;
            }
            Dictionary<string, string> para = new Dictionary<string, string>();
            foreach ( PropertyInfo p in typeof( T ).GetProperties() )
            {
                string value = p.GetValue( entity, null ).ToString();
                if ( !string.IsNullOrEmpty( value ) )
                {
                    para.Add( p.Name, value );
                }
            }
            return para;
        }

 

posted on 2013-08-14 16:57  而立未立  阅读(316)  评论(0编辑  收藏  举报