From 1a5da5718785158730268f8e41d0ca49fab97e3c Mon Sep 17 00:00:00 2001 From: falcon <9504402@qq.com> Date: Thu, 14 Jul 2022 09:01:38 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E5=86=99=E7=B1=BB=E5=9E=8B=E8=BD=AC?= =?UTF-8?q?=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Falcon.SugarApi.Test/ObjectExtendTest.cs | 8 ++++++++ Falcon.SugarApi/ObjectExtend.cs | 24 +++++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Falcon.SugarApi.Test/ObjectExtendTest.cs b/Falcon.SugarApi.Test/ObjectExtendTest.cs index 0eb318a..0ca543f 100644 --- a/Falcon.SugarApi.Test/ObjectExtendTest.cs +++ b/Falcon.SugarApi.Test/ObjectExtendTest.cs @@ -33,6 +33,14 @@ namespace Falcon.SugarApi.Test Assert.IsTrue(t.ica.ItemA == "itema"); Assert.IsTrue(t.ica.Equals(s.ica)); } + + [TestMethod] + public void ChangeTypeTest() { + int s = 1; + var t = s.ChangeType(typeof(int)); + Console.WriteLine(t.GetType().FullName); + Assert.IsTrue(t.GetType().Equals(typeof(int))); + } } public class SourceClass diff --git a/Falcon.SugarApi/ObjectExtend.cs b/Falcon.SugarApi/ObjectExtend.cs index f0d08d4..e5653a2 100644 --- a/Falcon.SugarApi/ObjectExtend.cs +++ b/Falcon.SugarApi/ObjectExtend.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -22,7 +23,8 @@ namespace Falcon.SugarApi join t in target.GetType().GetProperties() on s.Name equals t.Name select new { s, t }; foreach (var item in all) { - item.t.SetValue(target, Convert.ChangeType(item.s.GetValue(source), item.t.PropertyType)); + //item.t.SetValue(target, Convert.ChangeType(item.s.GetValue(source), item.t.PropertyType)); + item.t.SetValue(target,item.s.GetValue(source).ChangeType(item.t.PropertyType)); } return source; } @@ -38,5 +40,25 @@ namespace Falcon.SugarApi source.CloneTo(target); return target; } + + /// + /// 将对象转换成另一类型,如果转换失败可能返回null。 + /// + /// 原对象 + /// 目标类型 + /// 转换后的类型 + public static object? ChangeType(this object? source,Type targetType) { + if (targetType == null) { + throw new ArgumentNullException("targetType"); + } + if (source==null) { + return null; + } + if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { + NullableConverter nullableConverter = new NullableConverter(targetType); + targetType = nullableConverter.UnderlyingType; + } + return Convert.ChangeType(source, targetType); + } } }