11using System ;
22using System . Collections . Generic ;
33using System . Dynamic ;
4- using System . Linq ;
54using System . Reflection ;
6- using System . Threading . Tasks ;
75
86namespace Routine . APi . Helpers
97{
108 //Object 的拓展方法
119 //用于查询单个数据时的数据塑形(视频P39)
1210 public static class ObjectExtensions
1311 {
14- public static ExpandoObject ShapeData < TSource > ( this TSource source , string fields )
12+ public static ExpandoObject ShapeData < TSource > ( this TSource source , string fields )
1513 {
1614 if ( source == null )
1715 {
1816 throw new ArgumentNullException ( nameof ( source ) ) ;
1917 }
2018
19+ //理解 ExpandoObject 的使用 https://blog.csdn.net/u010178308/article/details/79773704
2120 var expandoObj = new ExpandoObject ( ) ;
2221
22+ //如果没有 fields 字符串指定属性,返回所有属性
2323 if ( string . IsNullOrWhiteSpace ( fields ) )
2424 {
25- var propertyInfos = typeof ( TSource ) . GetProperties ( BindingFlags . IgnoreCase
26- | BindingFlags . Public
25+ //获得 TSource 的属性
26+ var propertyInfos = typeof ( TSource ) . GetProperties ( BindingFlags . IgnoreCase //忽略属性名大小写
27+ | BindingFlags . Public //搜索公共成员
2728 | BindingFlags . Instance ) ;
28- foreach ( var propertyInfo in propertyInfos )
29+ foreach ( var propertyInfo in propertyInfos )
2930 {
3031 var propertyValue = propertyInfo . GetValue ( source ) ;
3132 ( ( IDictionary < string , object > ) expandoObj ) . Add ( propertyInfo . Name , propertyValue ) ;
3233 }
3334 }
35+ //如果有 fields 字符串指定属性,返回指定的属性
3436 else
3537 {
3638 var fieldsAfterSpilt = fields . Split ( "," ) ;
37- foreach ( var field in fieldsAfterSpilt )
39+ foreach ( var field in fieldsAfterSpilt )
3840 {
3941 var propertyName = field . Trim ( ) ;
42+ //获得 fields 字符串指定的 TSource 中的各属性
4043 var propertyInfo = typeof ( TSource ) . GetProperty ( propertyName ,
41- BindingFlags . IgnoreCase
42- | BindingFlags . Public
44+ BindingFlags . IgnoreCase //忽略属性名大小写
45+ | BindingFlags . Public //搜索公共成员
4346 | BindingFlags . Instance ) ;
4447 if ( propertyInfo == null )
4548 {
@@ -54,4 +57,4 @@ public static ExpandoObject ShapeData<TSource>(this TSource source,string fields
5457 return expandoObj ;
5558 }
5659 }
57- }
60+ }
0 commit comments