日期时间可空问题

本文关键字:问题 时间 日期 | 更新日期: 2023-09-27 18:15:06

我发送的是datetime to a function:

MyFunction((DateTime)MethodDateTime);

而我的MethodDateTimeDateTime数据类型并包含null值。

因为这个,在执行时,它给我错误nullable object must have a value

My Functions is this

MyFunction(DateTime abc)
{
    // Statements
}

所以冲浪后,我能理解的是,我强迫null到datetime。但这是我的问题,有时我得到空值作为日期时间,所以如何处理它?

当我直接通过datetime时,它显示

  1. The best overloaded method match for 'Big.Classes.QStr.MyFunction(System.DateTime)' has some invalid arguments
  2. cannot convert from 'System.DateTime?' to 'System.DateTime'

因此我选择了(DateTime)MethodDateTime

声明和初始化我的日期时间是DateTime? MethodDateTime = null;

编辑:

我所做的主要声明是:

    /// <summary>
    /// Get's or set's the MethodDateTime. If no MethodDateTime is there, this
    /// attribute is null.
    /// </summary>
    DateTime? MethodDateTime
    {
        get;
        set;
    }

日期时间可空问题

您可以简单地更改方法签名以接收一个可空的DateTime

MyFunction(DateTime? abc)
{
    if(abc.HasValue)
    {
        // your previous code
    }
    else
    {
       // Handle the NULL case
    }
}

然而,如果你真的不想改变你以前的代码,你可以简单地添加另一个方法,具有相同的名称,但可空的日期

MyFunction(DateTime? abc)
{
     Console.WriteLine("NULLABLE version called");
}
MyFunction(DateTime abc)
{
     Console.WriteLine("NOT NULLABLE version called");
}

通过这种方式,框架将调用正确的方法来查看传递的变量的数据类型

您需要使用类型为DateTime?而不是DateTime的参数声明您的函数,因此它是nullable

MyFunction(DateTime? abc)
{
   // Statements
}

如果您需要处理可能的空值,这是使用DateTime的唯一方法。对于可空类型,您有属性HasValue(优先检查null)和Value,例如:

MyFunction(DateTime? abc)
{
   if(abc.HasValue)
   {
     DateTime myDate = abc.Value;
   } else {
     // abc is null
   }
}

您可以使用null datetime datetime ?

如果我理解正确的话,您不希望将DateTime作为可空对象发送给MyFunction。然后你必须首先检查它是否为空,然后发送值。

if(MethodDateTime.HasValue)
{
   MyFunction(MethodDateTime.Value);
}
else
{
   // handle this case somehow
}

DateTime的值不能包含nullNullable<DateTime>(与DateTime?相同)本质上是一个包装器类,它允许您存储ValueType或null值。

你需要测试你的DateTime?价值:

if(MethodDateTime == null)
    MyFunction(DateTime.MinValue) //Pass in a sentinal value

或更改方法以允许为空:

MyFunction(DateTime? abc)
{
    ....

"然而我的MethodDateTime是DateTime数据类型并且包含空值。"

不,它是DateTime?而不是DateTime,这是System.Nullable<DateTime>的缩写。当你从DateTime?转换为DateTime时,错误发生,它没有值。

if( MethodDateTime.HasValue)
{
    MyFunction(MethodDateTime.Value);
}
else
{
    //Handle error
}