c# - 更好地理解命名空间及其使用

标签 c# namespaces

一篇关于命名空间的文章说

Namespaces are C# program elements designed to help you organize your programs. They also provide assistance in avoiding name clashes between two sets of code. Implementing Namespaces in your own code is a good habit because it is likely to save you from problems later when you want to reuse some of your code. For example, if you created a class named Console, you would need to put it in your own namespace to ensure that there wasn't any confusion about when the System.Console class should be used or when your class should be used.



现在想象在上面的语句中我确实创建了一个 Console我的命名空间中的类称为:myNamespace .

现在,当有人想使用我的图书馆时,他/她将不得不这样做:
using myNamespace;

但很可能她需要做
using System;

也。

所以我们仍然有冲突。如果我输入 Console ,我指的是哪个控制台?
这个问题是如何使用命名空间解决的?

附注。额外的:还有命名空间是如何在幕后工作的:我记得在某处我读过编译器只是在函数前面加上命名空间来查找它们的定义?

这是那个?命名空间真的只是对代码进行分组的一种手段吗?

最佳答案

如果您使用这两个命名空间,则必须完全限定用法( System.Console() ),或使用命名空间/类型别名( Console2 )来消除类型的歧义。

using Console1 = myNamespace;
using Console2 = System;

public void MyMethod()
{
 Console1.Console(); // or myNamespace.Console()
 Console2.Console(); // or System.Console()
}

关于c# - 更好地理解命名空间及其使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37460555/

相关文章:

c++ - 是否可以在 C++ 中查看命名空间的所有内容?

xml - Oracle XMLQuery 插入不需要的命名空间

php - 使用 PHP 命名空间

c# - 在 asp.net 中使用客户端和服务器验证器仅显示客户端验证

c# - 如果我使用 MemoryStream 存储 0.5 GB 的数据 block 然后丢弃它,它会产生什么长期影响?

c# - DataBind 后 GridView 丢失 ViewState "SortExpression"

java - JAXB:如何注释类以便它们属于不同的 namespace ?

php - 类的动态加载无法解决命名空间/使用

c# - linq 中的数据透视表

c# - MAUI 中的 Xamarin nuget 包