我在使用System.DirectoryServices.AccountManagement时遇到了一些代码。
public DateTime? LastLogon { get; }
DateTime后面的问号是什么意思?
我找到了关于 ??运算符(C#参考)的参考资料,但那不是同一件事。(280Z28:这里是使用可空类型的正确链接。)
我在使用System.DirectoryServices.AccountManagement时遇到了一些代码。
public DateTime? LastLogon { get; }
DateTime后面的问号是什么意思?
我找到了关于 ??运算符(C#参考)的参考资料,但那不是同一件事。(280Z28:这里是使用可空类型的正确链接。)
缩写
Nullable<DateTime>
正如其他人提到的那样,这个问号语法使类型可为空。
在使用可空类型时需要记住几个关键点(摘自文档,但我认为在这里强调它们会很有帮助):
Value
和HasValue
。例如:
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
例如:
int? x = null;
int y = x ?? -1;
正如其他人所提到的,?
用于将值类型声明为可空。
这在以下几种情况下非常有用:
例如,考虑一个用于表示从客户那里收到的一组非强制性问题的反馈的类:
class CustomerFeedback
{
string Name { get; set; }
int? Age { get; set; }
bool? DrinksRegularly { get; set; }
}
使用可空类型来表示客户未回答Age
和DrinksRegularly
的问题。
在你提到的例子中,我会将null
值视为用户从未登录的LastLogon
。
这是一个 Nullable<DateTime>
的快捷方式。请注意,使用这些类型的方法不能暴露给 COM,因为它们使用泛型,尽管看起来似乎不是。