简体   繁体   中英

A using namespace directive can only be applied to namespaces

using System.Text.RegularExpressions;
using System.DateTime; 

DateTime returnedDate = DateTime.Now();

it give me error :

A using namespace directive can only be applied to namespaces; 
'System.DateTime' is a type not a namespace (line 1, pos 1)

where is my mistake?

where is my mistake?

It is here: using System.DateTime;

DateTime is a class inside System namespace, not a namespace. In C# you can apply using directive only to namespaces. Adding using XYZ to your program lets you omit the namespace prefix XYZ from classes inside that namespace - for example, to reference class XYZ.ABC you can write ABC . The using directory does not go down to class level, though (this is in contrast to Java's import directories, where .* at the end of the name is optional).

Fix this by replacing using System.DateTime; with using System;

EDIT : (in response to a comment by Karl-Johan Sjögren ) There is another using construct in C# that lets you create aliases of types. This construct takes class names, but requires you to specify a new name for them, like this:

using DT = System.DateTime;

Now you can use DT in place of System.DateTime .

You should use namespace like this way:

using system;

OR this way with out using namespace:

System.DateTime returnedDate = System.DateTime.Now();
using System; 

DateTime returnedDate = DateTime.Now();
using System; 

 DateTime returnedDate = DateTime.Now();

DateTime is a type which means its a class. C# keyword "using" can only be used with namespaces. so in order to use DateTime class in your code , you don't need to write like this.

using System.DateTime;

Rather than writing above line,Simply Include System Namespace like this.

using System;

And use DateTime class in code.

In C# 6 you can do

using static System.DateTime;

var now = Now;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM