我有一个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被初始化为一个字节。
有什么帮助或建议可以克服这个错误吗?
Value
属性来访问该值。 - vgrunow = new DateTime();
这一行,它可以完全安全地被删除,对您的代码没有任何影响。 - Lasse V. Karlsen