C#null DateTime可选参数

C#null DateTime可选参数,c#,datetime,C#,Datetime,我在C#中遇到了一个问题,我想将DateTime对象作为函数的可选参数传递,如下所示: public bool SetTimeToNow(DateTime? now = null) { if (now == null) { now = new DateTime(); now = DateTime.Now; } } 这很好,但当我现在想使用对象时,如下所示: seconds = ( byte ) now.Second; 我得到一个错误: 'S

我在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?
“System.Nullable”不包含
“Second”且没有接受类型为的第一个参数的扩展方法“Second”
无法找到“System.Nullable”(是否缺少使用
指令还是程序集引用?
顺便说一下,秒也被初始化为字节


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

由于数据类型是
DateTime?
(又称
Nullable
),您首先必须检查它是否有值(调用
.HasValue
),然后通过调用
值来访问其值:

seconds = (byte) = now.Value.Second;
(请注意,当
now
为空时,该代码将引发异常,因此您必须检查
HasValue
!)

或者,如果要将其设置为默认值:

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

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

您可以使用
运算符

seconds = (byte) (now?.Second ?? 0); // if seconds is type of byte
seconds = now?.Second; // if seconds is type of byte?
任何使用默认参数的方法对我来说都是不必要的。您可以使用方法重载,而不是使用可为空的日期时间

public bool SetTimeToNow()
{
   return SetTimeToNow(DateTime.Now); // use default time.
}

public bool SetTimeToNow(DateTime now)
{
    // Do other things outside if
}

您需要使用
value
属性访问该值。在将now设置为DateTime之后。现在您可以将DateTime?解析为DateTime。然后您可以使用now。其次(此时不再需要可为空的DateTime)。立即调用.value以获取不可为空的DateTime;)注意,您不需要
now=new DateTime(),该行可以安全地完全删除,它不会对您的代码产生影响。