コード例 #1
0
ファイル: CSharpExtension.cs プロジェクト: booksyi/Helpers
        /// <summary>
        /// 將自訂類型的 Properties 轉換成 Dictionary
        /// </summary>
        public static Dictionary <string, object> ToDictionary <T>(this T model, bool isComponentModel = false)
        {
            Dictionary <string, object> properties = new Dictionary <string, object>();
            var props = isComponentModel ?
                        CSharpHelper.GetMappedProperties <T>() :
                        model.GetType().GetProperties();

            foreach (PropertyInfo prop in props)
            {
                properties.Add(
                    isComponentModel ? CSharpHelper.GetColumnName(prop) : prop.Name,
                    prop.GetValue(model));
            }
            return(properties);
        }
コード例 #2
0
ファイル: CSharpExtension.cs プロジェクト: booksyi/Helpers
        /// <summary>
        /// 將自訂類型的 Properties 轉換成 Dictionary,
        /// 轉換可依照 Attribute 來執行自定義的處理邏輯
        /// </summary>
        public static Dictionary <string, object> ToDictionary <T, TAttr>(this T model, Func <object, IEnumerable <TAttr>, object> attrAdapter, bool isComponentModel = false) where TAttr : Attribute
        {
            Dictionary <string, object> properties = new Dictionary <string, object>();
            var props = isComponentModel ?
                        CSharpHelper.GetMappedProperties <T>() :
                        model.GetType().GetProperties();

            foreach (PropertyInfo prop in props)
            {
                string key   = isComponentModel ? CSharpHelper.GetColumnName(prop) : prop.Name;
                object value = prop.GetValue(model);
                IEnumerable <TAttr> attrs = prop.GetCustomAttributes <TAttr>();
                if (attrs.Any())
                {
                    value = attrAdapter(value, attrs);
                }
                properties.Add(key, value);
            }
            return(properties);
        }