From a3bd83ff037f4a2d9503055a42d8c189fe7f83c4 Mon Sep 17 00:00:00 2001
From: falcon <9504402@qq.com>
Date: Mon, 28 Nov 2022 09:49:49 +0800
Subject: [PATCH] =?UTF-8?q?=E6=89=A9=E5=B1=95object=E6=96=B9=E6=B3=95?=
=?UTF-8?q?=EF=BC=8C=E4=B8=BAnull=E6=97=B6=E6=8E=92=E9=99=A4=E5=BC=82?=
=?UTF-8?q?=E5=B8=B8?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Falcon.SugarApi.Test/ObjectExtendTest.cs | 10 ++++++++++
Falcon.SugarApi/ObjectExtend.cs | 19 ++++++++++++++++---
2 files changed, 26 insertions(+), 3 deletions(-)
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;
+ }
}
}