C# null DateTime 可选参数

标签 c# datetime

我在 C# 中遇到问题,我想将 DateTime 对象作为函数的可选参数传递:

public bool SetTimeToNow(DateTime? now = null)
{
    if (now == null)
    {
       now = new DateTime();
       now = DateTime.Now;
    }
}

效果很好,但是当我现在想按如下方式使用该对象时:

seconds = ( byte ) now.Second;

我得到一个错误错误:

'System.Nullable<System.DateTime>' does not contain a definition for
'Second' and no extension method 'Second' accepting a first argument of type
'System.Nullable<System.DateTime>' could be found (are you missing using 
 directive or an assembly reference?

顺便把seconds初始化为一个byte。

关于如何克服此错误的任何帮助或建议?

最佳答案

因为数据类型是DateTime? (又名 Nullable<DateTime> ),您首先必须检查它是否有值(调用 .HasValue )然后通过调用 Value 访问它的值:

seconds = (byte) = now.Value.Second;

(请注意,当 now 为 null 时,该代码将抛出异常,因此您必须检查 HasValue !)

或者,如果你想默认它:

seconds = (byte) = now.HasValue ? now.Value.Second : 0;

这与:

seconds = (byte) = now != null ? now.Value.Second : 0;

关于C# null DateTime 可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33299243/

相关文章:

c# - 在一列中具有不同类型控件的未绑定(bind)网格

c# - 将 C# 委托(delegate)声明放在它自己的文件中的什么位置?

c# - LINQ 传递 UTC 日期还是使用 DateTime.UtcNow?

r - 我如何绘制时间 (HH :MM:SS) in X axis in R

c# - C# 中的 Web 进度条

c# - 从 C# 项目导航到 VB.NET 项目中的类或方法时,有没有办法阻止显示 C# 元数据

java - 使用 dll 和 java jni4net 时出现 UnsatisfiedLinkError 异常

Postgresql - 获取相对于给定日期时间值最近的日期时间行

python - 如何解析时间戳(以毫秒为单位)

c# - 如何在 ASP.NET MVC 中的 View 上只显示 DATE 部分