扩展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

@ -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;
}
}
}