我在 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/