2010-12-18 41 views
4

从系统获取时间和日期为什么需要System.DateTime.Now? 正如你所看到的那样,在顶部已经声明了一个System名称空间。如果我只写DateTime.Now它不起作用。我刚才了解到,如果我们宣布“使用系统”,那么我们就不必申报或写的System.Console.WriteLine或System.DateTime.Now等.NET中的DateTime

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); 
     } 
    } 
} 

回答

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); 
     } 
    } 
} 
+0

你今晚很快达林:) – alexn 2010-12-18 16:58:28

+0

@alexn,是的,这是感谢啤酒:-) – 2010-12-18 17:00:20

+0

我看到了......谢谢 – 2010-12-18 17:08:29

3

因为你的项目类是在一个名为日期时间命名空间。该冲突意味着编译器将在名称空间DateTime中查找名为Now的类型,这显然不存在。

重命名你的命名空间,你不会有问题。