System.DateTime? vs System.DateTime [英] System.DateTime? vs System.DateTime

查看:158
本文介绍了System.DateTime? vs System.DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些代码,我需要从我的页面中的日历控件(Ajax工具包:日历扩展程序)中读取日期值。

I was writing to some code where I needed to read the date value from a Calendar control in my page (Ajax toolkit: calendar extender).

以下代码:

DateTime newSelectedDate = myCalendarExtender.SelectedDate;

提供以下错误:

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

然而,通过插入一个演员我可以得到代码工作:

However, by inserting a cast I can get the code to work:

DateTime newSelectedDate = (DateTime)myCalendarExtender.SelectedDate; // works fine!

日历控件的SelectedDate属性(Ajax工具包)将数据类型描述为系统。 DateTime?'...显然'?'与所有这些有关系。

The 'SelectedDate' property for the calendar control (Ajax toolkit) describes the data type as 'System.DateTime?' ... clearly the '?' has something to do with all of this.

当数据类型包含这个符号(?)时究竟发生了什么? ..我推测我可以将'SelectedDate'属性直接应用于'DateTime'类型的变量而不进行转换。

What exactly is happening when a data type contains this symbol (?)... I presumed that I could apply the 'SelectedDate' property straight into a variable of type 'DateTime' without casting.

谢谢

推荐答案

?表示该类型为空。详情请参阅 MSDN

? means that the type is nullable. For details, see e.g. MSDN

Nullable是围绕值类型的编译器支持的包装器,允许值类型变为null。

Nullable is a compiler-supported wrapper around value types that allows value types to become null.

要访问DateTime值,您需要执行以下:

To access the DateTime value, you need to do the following:

DateTime? dateOrNull = myCalendarExtender.SelectedDate;
if (dateOrNull != null)
{
    DateTime newSelectedDate = dateOrNull.Value;
}

这篇关于System.DateTime? vs System.DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆