From e849e2670c45c5ad3b47aad91ac17c277b7c2f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=B0=E6=96=87?= Date: Wed, 19 Feb 2020 09:25:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=B0=E5=AF=8CP39=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Routine.APi/Helpers/ObjectExtensions.cs | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Routine/Routine.APi/Helpers/ObjectExtensions.cs b/Routine/Routine.APi/Helpers/ObjectExtensions.cs index 178e085..b8044f0 100644 --- a/Routine/Routine.APi/Helpers/ObjectExtensions.cs +++ b/Routine/Routine.APi/Helpers/ObjectExtensions.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.Dynamic; -using System.Linq; using System.Reflection; -using System.Threading.Tasks; namespace Routine.APi.Helpers { @@ -11,35 +9,40 @@ namespace Routine.APi.Helpers //用于查询单个数据时的数据塑形(视频P39) public static class ObjectExtensions { - public static ExpandoObject ShapeData(this TSource source,string fields) + public static ExpandoObject ShapeData(this TSource source, string fields) { if (source == null) { throw new ArgumentNullException(nameof(source)); } + //理解 ExpandoObject 的使用 https://blog.csdn.net/u010178308/article/details/79773704 var expandoObj = new ExpandoObject(); + //如果没有 fields 字符串指定属性,返回所有属性 if (string.IsNullOrWhiteSpace(fields)) { - var propertyInfos = typeof(TSource).GetProperties(BindingFlags.IgnoreCase - | BindingFlags.Public + //获得 TSource 的属性 + var propertyInfos = typeof(TSource).GetProperties(BindingFlags.IgnoreCase //忽略属性名大小写 + | BindingFlags.Public //搜索公共成员 | BindingFlags.Instance); - foreach(var propertyInfo in propertyInfos) + foreach (var propertyInfo in propertyInfos) { var propertyValue = propertyInfo.GetValue(source); ((IDictionary)expandoObj).Add(propertyInfo.Name, propertyValue); } } + //如果有 fields 字符串指定属性,返回指定的属性 else { var fieldsAfterSpilt = fields.Split(","); - foreach(var field in fieldsAfterSpilt) + foreach (var field in fieldsAfterSpilt) { var propertyName = field.Trim(); + //获得 fields 字符串指定的 TSource 中的各属性 var propertyInfo = typeof(TSource).GetProperty(propertyName, - BindingFlags.IgnoreCase - | BindingFlags.Public + BindingFlags.IgnoreCase //忽略属性名大小写 + | BindingFlags.Public //搜索公共成员 | BindingFlags.Instance); if (propertyInfo == null) { @@ -54,4 +57,4 @@ public static ExpandoObject ShapeData(this TSource source,string fields return expandoObj; } } -} +} \ No newline at end of file