C# - using 语句的位置 [英] C# - Location of using statements

查看:36
本文介绍了C# - using 语句的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到很多来回的一件事是 using 语句应该放在 C# 代码文件中的什么地方 - 无论是在最外层的范围内还是在命名空间内.我知道 using 语句的位置会影响该文件中引用的范围,但我不明白的是,为什么在大多数情况下,有人希望在其命名空间中使用 using 语句.

One thing I have noticed a lot of back and forth on is where using statements should be placed in a C# code file- whether its in the outermost scope or inside a namespace. I understand that the location of the using statement affects the scope of the references within that file, but what I don't understand is why, in most cases, someone would ever want their using statements inside their namespace.

几乎所有情况下在单个文件中只存在一个命名空间声明,因此定义 using 语句的范围似乎/(是?)没用.如果在同一个文件中放置多个类型和多个命名空间,那么使用作用域语句就非常有意义,但我仍然看到很多这样的情况,即使在具有一个命名空间的文件中也是如此.为什么?

In almost all cases only one namespace declaration ever exists in a single file so scoping the using statements seems/(is?) useless. If one were placing multiple types and multiple namespaces in the same file then scoped using statements make perfect sense, yet I still see plenty of cases of this being done even in files with one namespace. Why?

using System;

namespace MyNamespace
{
    using System.Text;

    public class MyClass {
        // ...
    }
}

ASP 是在整个项目中看似不必要地完成此操作的一个示例.NET MVC 源代码.

推荐答案

将using"放在文件顶部是 Visual Studio 的默认方式.但是,推荐的方法是将using"语句放在命名空间内.甚至 MS 的 stylecop 也捕捉到了这一点,并说 VS 的默认方式是错误的.

Putting "using" at the top of the files is the default way of Visual Studio. However, the recommended approach is putting the "using" statements inside of the namespace. Even MS's stylecop catches this and says the default way of VS is wrong.

这两种技术都很好.

StyleCop 规则说:放置多个命名空间元素在单个文件中通常是一个坏主意,但如果这是完成,最好将所有在每个指令中使用指令命名空间元素,而不是全局位于文件顶部.这将严格限定命名空间,并且也将有助于避免那种上述行为.

StyleCop Rule says: Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.

需要注意的是,当代码已使用 using 指令编写放在命名空间之外,小心移动这些时应采取命名空间中的指令,以确保这不会改变代码的语义.正如所解释的上面,放置 using-alias 指令在命名空间元素内允许编译器选择冲突的类型当指令是放置在命名空间之外.

It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.

这里有一些链接供进一步审查:

Here's some links for further review:

这篇关于C# - using 语句的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆