C# 最佳实践 - 转换 int 时的最佳实践是什么?到整数
C# Best Practice - What is the best practice when converting int? to int
我有一个可以为 null 的 int,它来自一个存储过程,来自数据库,我知道它不会有 null 值。我已经完成了以下操作:
public List<EngineerDetails> GetCarouselEngineerDetailsList(int customerID)
{
using (var db = new MainEntities80())
{
var foo0= db.procedure().Select(s => new fooo()
{
foo= s.foo,
foo2 = s.foo2,
foo3 = s.foo3 ,
foo4 = s.foo4 ,
x = s.CurrentJobId.Value
}).ToList();
return foo0;
}
}
但我想知道,虽然我知道价值永远存在。在获取值之前进行检查是一种好习惯吗?也许用一个转弯的表情。
或者因为我们知道它不会为空,所以我们应该忘记检查吗?
如果 s.CurrentJobId
实际上为 null,则将抛出 InvalidOperationException
。这几乎总是 "the world is not the way I expect it to be" 情况下的最佳结果,因此按原样使用代码是有意义的。
您可以使用 CurrentJobID = s.CurrentJobID.GetValueOrDefault()
.
如果遇到 NULL,那么这将生成基础类型的默认值,对于数字,默认值始终为 0。
或者,如果您更愿意使用 'exceptional' 值,例如 -1,那么您可以使用 CurrentJobID = s.CurrentJobID.GetValueOrDefault(-1)
。
if (s.CurrentJobID.HasValue)
{
CurrentJobID = s.CurrentJobID.Value
}
你可以这样做:
int result = s.CurrentJobId?? Int32.MinValue;
这将确保将 x 的值分配给 result,但如果 s.CurrentJobId 为 null,则会将 Int32.MinValue 分配给它。
它将防止抛出异常,之后您可以通过检查 Int32.MinValue.
来验证它是否为 null
但是,如果值确实不应该为 null,则抛出异常并快速失败是更好的选择。
我有一个可以为 null 的 int,它来自一个存储过程,来自数据库,我知道它不会有 null 值。我已经完成了以下操作:
public List<EngineerDetails> GetCarouselEngineerDetailsList(int customerID)
{
using (var db = new MainEntities80())
{
var foo0= db.procedure().Select(s => new fooo()
{
foo= s.foo,
foo2 = s.foo2,
foo3 = s.foo3 ,
foo4 = s.foo4 ,
x = s.CurrentJobId.Value
}).ToList();
return foo0;
}
}
但我想知道,虽然我知道价值永远存在。在获取值之前进行检查是一种好习惯吗?也许用一个转弯的表情。 或者因为我们知道它不会为空,所以我们应该忘记检查吗?
如果 s.CurrentJobId
实际上为 null,则将抛出 InvalidOperationException
。这几乎总是 "the world is not the way I expect it to be" 情况下的最佳结果,因此按原样使用代码是有意义的。
您可以使用 CurrentJobID = s.CurrentJobID.GetValueOrDefault()
.
如果遇到 NULL,那么这将生成基础类型的默认值,对于数字,默认值始终为 0。
或者,如果您更愿意使用 'exceptional' 值,例如 -1,那么您可以使用 CurrentJobID = s.CurrentJobID.GetValueOrDefault(-1)
。
if (s.CurrentJobID.HasValue)
{
CurrentJobID = s.CurrentJobID.Value
}
你可以这样做:
int result = s.CurrentJobId?? Int32.MinValue;
这将确保将 x 的值分配给 result,但如果 s.CurrentJobId 为 null,则会将 Int32.MinValue 分配给它。
它将防止抛出异常,之后您可以通过检查 Int32.MinValue.
来验证它是否为 null但是,如果值确实不应该为 null,则抛出异常并快速失败是更好的选择。