最简单的检查方法是确定Type是否为空(包括string)
本文关键字:包括 string 是否 Type 检查 方法 最简单 | 更新日期: 2023-09-27 18:08:19
检查某个类型是否可为空的最佳方法是什么?
一些建议的代码无法测试其他类型,特别是字符串。
!certainType.IsValueType || Nullable.GetUnderlyingType(certainType) != null
最简单的方法:
public static bool IsNullable(this Type type)
{
if (type.IsValueType) return Activator.CreateInstance(type) == null;
return true;
}
这些是我的单元测试,都通过了
IsNullable_String_ShouldReturn_True
IsNullable_Boolean_ShouldReturn_False
IsNullable_Enum_ShouldReturn_Fasle
IsNullable_Nullable_ShouldReturn_True
IsNullable_Class_ShouldReturn_True
IsNullable_Decimal_ShouldReturn_False
IsNullable_Byte_ShouldReturn_False
IsNullable_KeyValuePair_ShouldReturn_False
实际单元测试
[TestMethod]
public void IsNullable_String_ShouldReturn_True()
{
var typ = typeof(string);
var result = typ.IsNullable();
Assert.IsTrue(result);
}
[TestMethod]
public void IsNullable_Boolean_ShouldReturn_False()
{
var typ = typeof(bool);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_Enum_ShouldReturn_Fasle()
{
var typ = typeof(System.GenericUriParserOptions);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_Nullable_ShouldReturn_True()
{
var typ = typeof(Nullable<bool>);
var result = typ.IsNullable();
Assert.IsTrue(result);
}
[TestMethod]
public void IsNullable_Class_ShouldReturn_True()
{
var typ = typeof(TestPerson);
var result = typ.IsNullable();
Assert.IsTrue(result);
}
[TestMethod]
public void IsNullable_Decimal_ShouldReturn_False()
{
var typ = typeof(decimal);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_Byte_ShouldReturn_False()
{
var typ = typeof(byte);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_KeyValuePair_ShouldReturn_False()
{
var typ = typeof(KeyValuePair<string, string>);
var result = typ.IsNullable();
Assert.IsFalse(result);
}