gpt4 book ai didi

c# - "DateTime?"和 "DateTime"之间的差异。 (试图从日期选择器中获取值(value))

转载 作者:行者123 更新时间:2023-11-30 18:58:58 25 4
gpt4 key购买 nike

我对 WPFC# 很陌生,所以不要怪我问这个可能很愚蠢的问题。

我的 WPF 应用有两个日期选择器。我想在 DateTime 发生变化时从中获取它,并将其用作应用程序中其他一些东西的变量。所以我对他们每个人都有这样的东西(方法是由 VS 自动生成的):

private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
date1 = datePicker1.SelectedDate;
}

但问题是日期选择器中的日期格式是 DateTime? 而不是 DateTime 我真的不知道那里的问号是什么意思以及为什么有没有。我尝试了一些研究,但没有找到任何对我有帮助的东西。如果您看到从该日期选择器获取日期的更好方法,您也可以帮助我。我只是在我的 xaml.cs 代码中需要它,而不是在 xaml 中,而且我并不真正喜欢使用绑定(bind),因为我不确定在这种情况下它是否按我需要的方式工作。

感谢您的回答。

编辑:我想添加它向我显示此错误的信息:

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

最佳答案

日期时间 ?Nullable DateTime,它可以保存空值。对于您的情况,您可以这样做:

private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
if(datePicker1.SelectedDate.HasValue)
date1 = datePicker1.SelectedDate.Value;
}

Nullable<T> C#

In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null.

关于c# - "DateTime?"和 "DateTime"之间的差异。 (试图从日期选择器中获取值(value)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16397228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com