扩展object方法,为null时排除异常

This commit is contained in:
falcon 2022-11-28 09:49:49 +08:00
parent 0faab483a9
commit a3bd83ff03
2 changed files with 26 additions and 3 deletions

View File

@ -41,6 +41,16 @@ namespace Falcon.SugarApi.Test
Console.WriteLine(t.GetType().FullName);
Assert.IsTrue(t.GetType().Equals(typeof(int)));
}
/// <summary>
/// 测试对象为null则会抛出异常
/// </summary>
[TestMethod]
public void ThrowNullExceptionWhenNullTest() {
var obj = new object();
obj.ThrowNullExceptionWhenNull();
obj = null;
Assert.ThrowsException<ArgumentNullException>(() => obj.ThrowNullExceptionWhenNull());
}
}
public class SourceClass

View File

@ -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
/// <param name="source">原对象</param>
/// <param name="targetType">目标类型</param>
/// <returns>转换后的类型</returns>
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);
}
/// <summary>
/// 如果对象为null则抛出异常
/// </summary>
/// <param name="obj">检测对象</param>
/// <returns>对象本身</returns>
/// <exception cref="ArgumentNullException">对象为null</exception>
public static object? ThrowNullExceptionWhenNull(this object? obj) {
if (obj == null) {
throw new ArgumentNullException();
}
return obj;
}
}
}