C# 可选的 null DateTime 参数

4
我有一个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被初始化为一个字节。

有什么帮助或建议可以克服这个错误吗?


3
您需要使用 Value 属性来访问该值。 - vgru
在将now设置为DateTime.Now之后,您可以将DateTime?解析为DateTime。然后,您可以使用now.Second(此时不再需要可空的DateTime)。调用now.Value以获取非空的DateTime ;) - Matthias Burger
1
请注意,您不需要 now = new DateTime(); 这一行,它可以完全安全地被删除,对您的代码没有任何影响。 - Lasse V. Karlsen
2个回答

2

由于数据类型是DateTime?(也称为Nullable<DateTime>),您首先需要检查它是否有值(调用.HasValue),然后通过调用Value来访问其值:

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

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

或者,如果您想要默认值:

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

这与以下内容相同:

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

1
您可以使用.???运算符。
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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接