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);
+ }
}
}