[FxCop.设计规则]10. 类型应该被声明在命名空间中
2005-06-09 20:15
459 查看
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 namespace GoodSpace 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?翻译正确吗?)中的相关类型。一个不再任何命名的命名空间中的类型放在全局命名空间中,这样将不能被其他代码所引用(原文翻译过来如此,但是译者尝试后发现可以使用,并且不需要引用任何命名空间。)。修复:
将这个类型放到一个命名的命名空间中。例外:
尽量不要忽略这条校验,但是只要这个程序集不会被其他程序集使用,违反这条规则并不影响代码的安全性。例程:
原文的例子演示了一个库中包含两个同名类型,一个在全局命名空间中,另一个在命名的命名空间中。在第二段代码中演示了如何调用它们。相关文章推荐
- [FxCop.设计规则]10. 类型应该被声明在命名空间中
- [FXCOP.设计规则]5. 避免命名空间中包含太少的类型
- [FxCop.设计规则]5. 避免命名空间中包含太少的类型
- [FxCop.设计规则]5. 避免命名空间中包含太少的类型
- [FxCop.设计规则]8. 也许参数类型应该是基类型
- [FxCop.设计规则]8. 也许参数类型应该是基类型
- [FxCop.设计规则]2. 程序集应该拥有有效的强命名
- [FxCop.设计规则]1. 抽象类不应该拥有构造函数
- [FxCop.设计规则]9. 事件句柄声明不恰当
- [FxCop.设计规则]11. 不应该使用默认参数
- [FxCop.设计规则]2. 程序集应该拥有一个有效的强名称
- [FxCop.设计规则]7. 集合类应该实现泛型接口
- [FxCop.设计规则]11. 不应该使用默认参数
- [FxCop.设计规则]1. 抽象类型不应具有构造函数
- [FxCop.设计规则]2. 程序集应该拥有一个有效的强名称
- [FxCop.设计规则]16. 不要在封闭类中声明虚成员
- 浅谈HTML的文档类型声明和html命名空间
- [FxCop.设计规则]15. 不要在范型类中声明静态成员
- C++ Primer学习笔记6 标准库类型(命名空间的using声明、标准库string类型)
- 第一部分 基本语言 第三章 标准库类型(命名空间的using声明)