这个问题已经在这里有了答案: > Which is preferred: Nullable<T>.HasValue or Nullable<T> != null? 6个
我想问一个有关控制datetime的空值的问题.
我想问一个有关控制datetime的空值的问题.
if (mydatetime != null)
要么
if(mydatetime.hasvalue)
哪个更好或更合适?为什么?
谢谢.
最佳答案
第一个比较!= null一直是有效的比较,因为只有当变量声明为Nullable时才可以使用第二个比较,换句话说,只有当DateTime变量声明为Nullable时才可以使用与.HasValue的比较.
例如 :
DateTime dateInput;
// Will set the value dynamically
if (dateInput != null)
{
// Is a valid comparison
}
if (dateInput.HasValue)
{
// Is not a valid comparison this time
}
在哪里
DateTime? dateInput; // nullable declaration
// Will set the value dynamically
if (dateInput != null)
{
// Is a valid comparison
}
if (dateInput.HasValue)
{
// Is also valid comparison this time
}
相关文章
- 首页> C#>如何使用.NET的string.Join方法,当一个值为null时打印一个自定义字符串?
- 首页> C#>什么是服务,为什么要在ASP.NET Core中添加它们?
- 首页> C#> log4net AdoNetAppender在数据库中插入“ Null”字符串,而不是null
- 首页> C#> DateTime.ParseExact没有做我想做的事
- 首页> C#>如何获得下个月的每一天的名字?
- 首页> C#> Page.FindControl返回空为DIV
- 首页> C#> Convert.ToString(DateTime)产生英国格式,而不是美国
- 首页> C#> NewtonSoft的JsonConvert.DeserializeObject返回所有属性为空
转载注明原文:首页> C#> DateTime.hasvalue vs datetime == null,哪个更好,为什么 - 代码日志