简体   繁体   English

使用和名称空间

[英]Using and namespace

Where to place using System or other namespaces? 使用System或其他名称空间放置在哪里? Which is the correct or the better way to write code and why? 哪种是正确的或更好的代码编写方式,为什么? According to my c# trainer it is the second, but everywhere I see the first one. 根据我的C#培训师的说法,它是第二个,但是到处都可以看到第一个。

using System;
namespace Program
{
    class SomeClass
    {
    }
}

or 要么

namespace Program
{
using System;

    class SomeClass
    {
    }
}

According to my c# trainer it is the second, but everywhere I see the first one. 根据我的C#培训师的说法,它是第二个,但是到处都可以看到第一个。

The scope of a using directive is limited to the file in which it appears. using指令的范围仅限于出现该指令的文件。

Create a using alias to make it easier to qualify an identifier to a namespace or type. 创建using别名,以使将标识符限定为名称空间或类型变得更加容易。 The right side of a using alias directive must always be a fully-qualified type regardless of the using directives that come before it. using别名指令的右侧必须始终是标准类型,而不管其前面的using指令如何。

Create a using directive to use the types in a namespace without having to specify the namespace. 创建using指令以使用名称空间中的类型,而不必指定名称空间。 A using directive does not give you access to any namespaces that are nested in the namespace you specify. using指令不能使您访问嵌套在指定名称空间中的任何名称空间。

Refer: http://msdn.microsoft.com/en-us/library/sf0df423.aspx 参考: http : //msdn.microsoft.com/en-us/library/sf0df423.aspx

It is your choice. 这是你的选择。 The second can be handy if you have a code file with multiple namespaces, but only want to use a namespace import within one of these namespaces. 如果您有一个具有多个名称空间的代码文件,但只想在这些名称空间之一中使用名称空间导入,则第二个选项可能很方便。 However, most coding guidelines that I have seen so far specify that a file may only contain one namespace at most and the usings at the top of the file, in alphabetic order. 但是,到目前为止,我所见的大多数编码指南都指定一个文件最多只能包含一个名称空间,而使用最多的是按字母顺序排列的文件顶部。

Stylecop by default requires you to put usings inside namespaces - see here ; 默认情况下,Stylecop要求您将uses放在名称空间中-参见此处 for the following reason: (from linked page): 由于以下原因:(来自链接页面):

There are subtle differences between placing using directives within a namespace element, rather than outside of the namespace, including: 将使用指令放置在名称空间元素内而不是在名称空间之外存在细微的差异,包括:

  1. Placing using-alias directives within the namespace eliminates compiler confusion between conflicting types. 将using-alias指令放在名称空间中可消除编译器在冲突类型之间的混淆。

  2. When multiple namespaces are defined within a single file, placing using directives within the namespace elements scopes references and aliases. 当在单个文件中定义多个名称空间时,使用指令在名称空间元素中的放置将作用域引用和别名。

使用始终位于文档的顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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