【发布时间】:2010-02-11 18:05:00
【问题描述】:
当我需要将值加载到类和结构中时,我经常使用Nullable<T> 类型,当我需要它们可以为空时,例如从数据库加载一个可以为空的值(如下例所示)。
考虑一下这段代码:
public class InfoObject
{
public int? UserID { get; set; }
}
// Load the ID into an SqlInt32
SqlInt32 userID = reader.GetSqlInt32(reader.GetOrdinal("intUserID"));
当我需要将值加载到可空属性中时,有时我会这样做:
infoObject.UserID = userID.IsNull ? (int?)null : userID.Value;
有时我会这样做:
infoObject.UserID = userID.IsNull ? new int?() : userID.Value;
虽然它们达到了相同的结果,但我想看看是否有人知道在性能、最小 IL 代码、最佳实践等方面,(int?)null 和 new int?() 之间使用哪个更好?
一般来说,我一直喜欢上面代码的new int?() 版本,但我不确定转换(int?)null 是否比new int?() 更快地解决编译器。
干杯!
【问题讨论】:
标签: c# performance nullable