扩展object方法,为null时排除异常
This commit is contained in:
parent
0faab483a9
commit
a3bd83ff03
|
@ -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
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user