C#-名称空间中的类型声明 [英] C# - Declaration of types within a namespace
问题描述
在命名空间中而不是在类中声明类型的可能用途.
what could be a possible use of declaring types within a namespace but not in a class.
例如:
namespace Test
{
public delegate void Ispossible();
}
这是有效的&不会产生任何编译错误,但我想不出为什么我们会这样声明而不是在类内部进行编译.
This is valid & does not generate any compilation errors but i can't think of why we would declare it this way as opposed to inside a class.
推荐答案
名称空间是.NET中的高级组织单位.
A namespace is a high-level unit of organization within .NET.
在类中声明类型通常不被接受(但是,与所有事物一样,这并不是100%的规则),因为这会使类型更紧密地耦合并且更难找到.
Declaring types within classes is typically frowned upon (but, as with all things, it's not a 100% rule) because it can make the types more tightly coupled and more difficult to find.
VB.NET模块有些例外( edit :它们实际上更多地是编译器技巧/语法糖),但通常.NET生态系统中的所有内容都包含在名称空间中
VB.NET Modules are somewhat of an exception (edit: they're really more of a compiler trick/syntactical-sugar), but normally everything in the .NET ecosystem is contained in a namespace.
您的示例可以重用;如果它在一个类中,则意味着该委托只能由该类使用,并且可能导致不必要地引入重复的委托.
Your example lends itself to reuse; if it were within a class then it would imply that delegate should only be used by that class and would likely lead to duplicate delegates needlessly being introduced.
更新:当仅使用少数类型的名称空间时,名称空间似乎用处不大,但是如果没有名称空间,那么任何规模的项目都将是组织的灾难.想象一下.NET框架没有名称空间,一个(可能很久就过时了)的数目使该框架的类型为3500.
Update: When working with only a handful of types namespaces don't seem of much use, but without them a project of any size would be an organizational catastrophe. Imagine the .NET framework without namespaces, one (probably long outdated) count puts the framework at 3500 Types.
命名空间就像文档的文件夹或抽屉.一些松散的纸张很容易管理,但是如果您有很多页面,那么找到所需的页面会很痛苦.
Namespaces are like folders or drawers for documents; a few loose papers are easy to manage but if you have many pages then finding the one you need becomes painful.
阅读文档,它简短而又不十分复杂(都不是名称空间),但是有几个不错的地方
Give the documentation a read, it's short and not terribly complicated (neither are namespaces) but has a couple decent points MSDN - Namespace (c#)
这篇关于C#-名称空间中的类型声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!