C# - Declaration of types within a namespace

▼魔方 西西 提交于 2020-01-03 16:44:14

问题


what could be a possible use of declaring types within a namespace but not in a class.

For ex:

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.


回答1:


A namespace is a high-level unit of organization within .NET.

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 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.


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#)




回答2:


If it is a multi purpose delegate such as Func<TResult>, EventHandler which is not related to a particular class then you should declare it in the namespace directly.




回答3:


Your phrasing ("what could be a possible use of declaring types within a namespace but not in a class."), indicates that you draw a distinction betweens "types" and "classes". There is none. A class is a type.

So, under what conditions would you want to declare a class directly in a namespace (i.e, the way it is most commonly done) ? These same reasons apply to other kinds of types.




回答4:


Both namespaces and classes can be used to organize information in hierarchy. However namespaces allow to distribute definition across dll boundaries, but classes do not. Also classes require to put class name before type name, but namespaces allow to use keyword "using".

So if you want to define delegates in one namespace in different dlls, you use namespaces.

If you want to force people to prefix type name with any other name without being able to rely on namespace context then you use classes.



来源:https://stackoverflow.com/questions/2343449/c-sharp-declaration-of-types-within-a-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!