diff --git a/Falcon.SugarApi.Test/ObjectExtendTest.cs b/Falcon.SugarApi.Test/ObjectExtendTest.cs
index 0ca543f..017133a 100644
--- a/Falcon.SugarApi.Test/ObjectExtendTest.cs
+++ b/Falcon.SugarApi.Test/ObjectExtendTest.cs
@@ -41,6 +41,16 @@ namespace Falcon.SugarApi.Test
Console.WriteLine(t.GetType().FullName);
Assert.IsTrue(t.GetType().Equals(typeof(int)));
}
+ ///
+ /// 测试对象为null则会抛出异常
+ ///
+ [TestMethod]
+ public void ThrowNullExceptionWhenNullTest() {
+ var obj = new object();
+ obj.ThrowNullExceptionWhenNull();
+ obj = null;
+ Assert.ThrowsException(() => obj.ThrowNullExceptionWhenNull());
+ }
}
public class SourceClass
diff --git a/Falcon.SugarApi/ObjectExtend.cs b/Falcon.SugarApi/ObjectExtend.cs
index e5653a2..506c65c 100644
--- a/Falcon.SugarApi/ObjectExtend.cs
+++ b/Falcon.SugarApi/ObjectExtend.cs
@@ -24,7 +24,7 @@ namespace Falcon.SugarApi
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,item.s.GetValue(source).ChangeType(item.t.PropertyType));
+ item.t.SetValue(target, item.s.GetValue(source).ChangeType(item.t.PropertyType));
}
return source;
}
@@ -47,11 +47,11 @@ namespace Falcon.SugarApi
/// 原对象
/// 目标类型
/// 转换后的类型
- public static object? ChangeType(this object? source,Type targetType) {
+ public static object? ChangeType(this object? source, Type targetType) {
if (targetType == null) {
throw new ArgumentNullException("targetType");
}
- if (source==null) {
+ if (source == null) {
return null;
}
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
@@ -60,5 +60,18 @@ namespace Falcon.SugarApi
}
return Convert.ChangeType(source, targetType);
}
+
+ ///
+ /// 如果对象为null则抛出异常
+ ///
+ /// 检测对象
+ /// 对象本身
+ /// 对象为null
+ public static object? ThrowNullExceptionWhenNull(this object? obj) {
+ if (obj == null) {
+ throw new ArgumentNullException();
+ }
+ return obj;
+ }
}
}