10. 类型应该被声明在命名空间中
翻译概述:
命名空间的概念在C++中已经存在,但是对于大多数C++程序员来说,命名空间却很少被用到,C++程序员更喜欢在一组相关的类型前面添加相同的缩写,当项目变得越来越大时,这种传统的处理方式就很难适应软件系统规模。因此,在新的面向对象开发语言中无一例外的强化了命名空间的概念。
毋庸置疑,将类型放在全局命名空间中是一个很不好的设计。FxCop设计规则的第十条就对这条规则进行了校验。
原文引用:
Declare types in namespaces
Rule Description Types are declared within namespaces to prevent name collisions, and as a way of organizing related types in an object hierarchy. Types outside any named namespace are in a global namespace that cannot be referenced in code. How to Fix Violations To fix a violation of this rule, place the type in a namespace. When to Exclude Messages While it is never necessary to exclude a message from this rule, it is safe to do this when the assembly will never be used with other assemblies. Example Code The following example shows a library with a type incorrectly declared outside a namespace, and a type with the same name declared in a namespace. [C#] using System;
// Violates rule: DeclareTypesInNamespaces. public class Test { public override string ToString() { return "Test does not live in a namespace!"; } }
namespace GoodSpace { public class Test { public override string ToString() { return "Test lives in a namespace!"; } } }
The following application uses the library defined previously. Note that the type declared outside a namespace is created when the name Test is not qualified by a namespace. Note also that to access the Test type in Goodspace, the namespace name is required. [C#] using System; using GoodSpace;
namespace ApplicationTester { public class MainHolder { public static void Main () { Test t1 = new Test();
Console.WriteLine (t1.ToString());
GoodSpace.Test t2 = new GoodSpace.Test();
Console.WriteLine (t2.ToString()); } } } This example produces the following output. Test does not live in a namespace! Test lives in a namespace!
|
引起的原因:
一个公共的或保护的类型没有定义在命名的命名空间中(非全局命名空间)
描述:
将类型定义在命名空间中,可以避免命名冲突,同时,提供了一种有效的方式组织一个对象层次(hierarchy?翻译正确吗?)中的相关类型。一个不再任何命名的命名空间中的类型放在全局命名空间中,这样将不能被其他代码所引用(原文翻译过来如此,但是译者尝试后发现可以使用,并且不需要引用任何命名空间。)。
修复:
将这个类型放到一个命名的命名空间中。
例外:
尽量不要忽略这条校验,但是只要这个程序集不会被其他程序集使用,违反这条规则并不影响代码的安全性。
例程:
原文的例子演示了一个库中包含两个同名类型,一个在全局命名空间中,另一个在命名的命名空间中。在第二段代码中演示了如何调用它们。