C# using 命名空间指令只能应用于命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17697692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:13:41  来源:igfitidea点击:

A using namespace directive can only be applied to namespaces

c#.netdatetime

提问by Alex

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?

我的错误在哪里?

采纳答案by Praveen Prasannan

using System; 

DateTime returnedDate = DateTime.Now();

回答by dasblinkenlight

where is my mistake?

我的错误在哪里?

It is here: using System.DateTime;

是这里: using System.DateTime;

DateTimeis a class inside Systemnamespace, not a namespace. In C# you can apply usingdirective only to namespaces. Adding using XYZto your program lets you omit the namespace prefix XYZfrom classes inside that namespace - for example, to reference class XYZ.ABCyou can write ABC. The usingdirectory 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).

DateTimeSystem命名空间内的类,而不是命名空间。在 C# 中,您只能将using指令应用于命名空间。添加using XYZ到您的程序中,您可以XYZ从该名称空间内的类中省略名称空间前缀- 例如,XYZ.ABC您可以编写ABC. 但是,该using目录不会下降到类级别(这与 Java 的导入目录形成对比,其中.*名称的末尾是可选的)。

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

通过替换using System.DateTime;来解决这个问题using System;

EDIT :(in response to a comment by Karl-Johan Sj?gren) There is another usingconstruct 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:

编辑:(回应Karl-Johan Sj?gren的评论)usingC# 中有另一个结构可以让您创建类型的别名。此构造采用类名,但要求您为它们指定一个新名称,如下所示:

using DT = System.DateTime;

Now you can use DTin place of System.DateTime.

现在您可以使用DT代替System.DateTime.

回答by Santosh Panda

You should use namespace like this way:

您应该像这样使用命名空间:

using system;

OR this way with out using namespace:

或者这样不使用命名空间:

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

回答by James

using System; 

 DateTime returnedDate = DateTime.Now();

回答by Ammar

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.

DateTime 是一种类型,这意味着它是一个类。C# 关键字“using”只能与命名空间一起使用。所以为了在你的代码中使用 DateTime 类,你不需要这样写。

using System.DateTime;

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

而不是写在上面的行,只需像这样包含系统命名空间。

using System;

And use DateTime class in code.

并在代码中使用 DateTime 类。

回答by Ammar

In C# 6 you can do

在 C# 6 中你可以做

using static System.DateTime;

var now = Now;