什么是一个问题大关以下声明一个变量是什么意思?一个问题、大关、变量、声明

2023-09-03 00:43:22 作者:热情被耗尽

虽然在一个开源项目打转转,我尝试的的ToString 的DateTime对象是受阻于编译器。当我跳的定义,我看到这样的:

Whilst playing around in an open source project, my attempt to ToString a DateTime object was thwarted by the compiler. When I jumped to the definition, I saw this:

public DateTime? timestamp;

可能有人请赐教什么这就是所谓的,为什么它可能是有用的?

Might someone please enlighten me on what this is called and why it might be useful?

推荐答案

这是一个的可空类型。可空类型允许值类型(如 INT 和结构,如日期时间)包含空。

This is a nullable type. Nullable types allow value types (e.g. ints and structures like DateTime) to contain null.

是语法糖可空< D​​ateTime的> ,因为它的使用如此频繁

The ? is syntactic sugar for Nullable<DateTime> since it's used so often.

要叫的ToString()

if (timstamp.HasValue) {        // i.e. is not null
    return timestamp.Value.ToString();
}
else {
    return "<unknown>";   // Or do whatever else that makes sense in your context
}