[C#]关于DateTime的一点注意事项

本文详细介绍了在C#中如何正确处理DateTime类型的空值,包括直接声明DateTime变量时不允许赋空值的原因,以及通过添加问号使其可为空的具体实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们直接声明DateTime的话,是不允许直接赋值为空的,如下。
在这里插入图片描述
如果不赋值的话,会默认给一个日期,即"0001-01-01 00:00:00",如下

class Test
{
	public DateTime Dt { set; get; }
}
class Program
{
	static void Main(string[] args)
	{
		Test test = new Test();
        if (test.Dt == null)
        {
            Console.WriteLine("该日期为null");
        }
        else
        {
            Console.WriteLine("该日期不为null");
        }
        Console.WriteLine("内容:" + test.Dt);
        Console.ReadLine();
	}
}

控制台输出结果为
在这里插入图片描述

如果我们想让这个DateTime的变量赋值为空的话,可以在声明里边加个问号,如下

class Program
{
	static void Main(string[] args)
	{
		DateTime? dt = null;
        if (dt == null)
        {
            Console.WriteLine("该日期为null");
        }
        else
        {
            Console.WriteLine("该日期不为null");
        }
        Console.WriteLine("内容:" + dt);
        Console.ReadLine();
	}
}

或者

class Test
{
    public DateTime? Dt { set; get; }
}
class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        if (test.Dt == null)
        {
            Console.WriteLine("该日期为null");
        }
        else
        {
            Console.WriteLine("该日期不为null");
        }
        Console.WriteLine("内容:" + test.Dt);
        Console.ReadLine();
    }
}

运行结果为
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值