[FxCop.设计规则]10. 类型应该被声明在命名空间中
2005-06-09 20:15 Colin Han 阅读(2283) 评论(2) 编辑 收藏 举报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#] ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
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#] ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() This example produces the following output. Test does not live in a namespace! Test lives in a namespace! |
引起的原因:
一个公共的或保护的类型没有定义在命名的命名空间中(非全局命名空间)
描述:
将类型定义在命名空间中,可以避免命名冲突,同时,提供了一种有效的方式组织一个对象层次(hierarchy?翻译正确吗?)中的相关类型。一个不再任何命名的命名空间中的类型放在全局命名空间中,这样将不能被其他代码所引用(原文翻译过来如此,但是译者尝试后发现可以使用,并且不需要引用任何命名空间。)。
修复:
将这个类型放到一个命名的命名空间中。
例外:
尽量不要忽略这条校验,但是只要这个程序集不会被其他程序集使用,违反这条规则并不影响代码的安全性。
例程:
原文的例子演示了一个库中包含两个同名类型,一个在全局命名空间中,另一个在命名的命名空间中。在第二段代码中演示了如何调用它们。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix