【问题标题】:The type name 'Now' does not exist in the type 'DateTime'“DateTime”类型中不存在类型名称“Now”
【发布时间】:2017-12-02 02:49:07
【问题描述】:

我正在 Visual Studio 2017 中使用 Xamarin 和 C# 制作一个跨平台的测验应用程序。这行代码出现了问题:

DateTime today = new DateTime.Now;

Visual Studio 在.Now 下划线并声称“类型名称'Now' 不存在于类型'DateTime' 中。”

代码的目标是获取系统时间并将其显示在文本框中(以及为记事卡构造函数创建日期)。 由于.Now,Visual Studio 声明“类型名称‘Now’不存在于类型‘DateTime’中。

我也尝试使用System.DateTime.Now,但这并没有产生更好的结果,因为标题已经包含System。下面是模板,它是 XAML 页面的标准 C#:

namespace DenisQuiz.UWP
{
   // This page allows the user to create a new study set.
   public sealed partial class CreateNewStudySet : Page
   {
      DateTime today = new DateTime.Now;

      public CreateNewStudySet()
      {
         this.InitializeComponent();

         automaticTodaysDate.Text = today.ToString();
      }
   }
}

这无疑是一个简单的解决方案,但我查看了文档,似乎没有人遇到这个问题,并且文档建议了这个确切的用法:

DateTime localDate = DateTime.Now;

有没有办法纠正当前设置的问题,或者我必须使用其他方法来获取时间?

【问题讨论】:

    标签: c# xamarin cross-platform


    【解决方案1】:

    你做错了

                  DateTime today = new DateTime.Now;
    

    您必须新建 DateTime 对象。 https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx。在下面的示例中,我正在传递年、月和日。

                DateTime today = new DateTime(2017,12,1); // or other constructor
    

    或者简单地使用哪个返回 DateTime 实例,根据您的系统/服务器日期时间,当前年份、当前月份和当前日期。

                DateTime today = DateTime.Now;
    

    【讨论】:

    • 所以我没有创建new 对象,而是得到它。
    • DateTime.Now 将为您提供实例,因此无需使用new
    猜你喜欢
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2020-03-05
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多