在几乎所有情况下,单个文件中只有一个命名空间声明存在,因此,使用语句似乎/(is?)无效.如果一个人将多个类型和多个命名空间放在同一个文件中,那么使用语句的范围是完全正确的,但即使在具有一个命名空间的文件中,我仍然会看到很多情况.为什么?
using System; namespace MyNamespace { using System.Text; public class MyClass { // ... } }
这个在整个项目中完成的一个例子似乎是不必要的,就是ASP.NET MVC source.
解决方法
这两种技术都能正常工作.
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.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.
这里有一些链接进一步审查:
> Should ‘using’ statements be inside or outside the namespace?
> Is sa1200 All using directives must be placed inside the namespace (StyleCop) purely cosmetic?
> http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx
> http://blogs.msdn.com/sourceanalysis/pages/sa1200-usingdirectivesmustbeplacedwithinnamespace.aspx