在.NET中的日期时间处理

4
为什么需要使用 System.DateTime.Now 来获取系统时间和日期呢? 你会发现在顶部已经声明了一个 System 命名空间。如果我只写 DateTime.Now,它不起作用。我之前学过,如果我们声明“using System”,那么我们就不必声明或写 System.Console.WriteLine 或 System.DateTime.Now 等等。
using System;
using System.Text;

namespace DateTime
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The current date and time is " + System.DateTime.Now);
        }
    }
}
2个回答

11

这是因为你的命名空间已经被称为DateTime,与现有的类名冲突。所以你可以选择:

namespace DateTime
{
    using System;
    using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The current date and time is " + DateTime.Now);
        }
    }
}

或者为您自己的命名空间找到更好的命名约定,这是我建议您做的事情:

using System;
using System.Text;

namespace MySuperApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The current date and time is " + DateTime.Now);
        }
    }
}

3

由于您的Program类在名为DateTime的命名空间中。这种冲突意味着编译器将在您的命名空间DateTime中查找一个名为Now的类型,显然该类型不存在。

重命名您的命名空间即可解决问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接