gpt4 book ai didi

c# - 关于 C# 命名空间结构的困惑

转载 作者:太空狗 更新时间:2023-10-29 22:04:52 24 4
gpt4 key购买 nike

我对 C# 中命名空间的结构有点困惑我是 C# 和 WPF 的新手

当我创建一个新的 WPF 项目时,默认情况下这些命名空间包含在顶部

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

我对这些结构的理解感到困惑。我明白了

using System;

意味着我指的是系统命名空间

但是其他的呢

using System.Text;

这是什么意思?

  • 我正在访问名为“System.Text”的单个命名空间?
  • 或者我正在访问嵌套在“系统”命名空间内的“文本”命名空间?

此外,如果“Text”嵌套在“System”中,为什么只有“using System”包含所有命名空间?我们是否必须明确包含我们使用的每个命名空间?

最佳答案

Does using System.Text; mean that I'm using a single namespace named as "System.Text" or that I'm using the "Text" namespace nested inside "System" namespace?

后者。您正在使用嵌套在“系统”命名空间内的“文本”命名空间。

注意当你说

namespace Foo.Bar.Blah
{
class C
{
...

这只是一种简写方式

namespace Foo
{
namespace Bar
{
namespace Blah
{
class C
{
...

命名空间只有“简单”的名字。

should we have an explicit 'using' directive for every namespace we use?

通常你会这样做,是的。在某些情况下您可能不想这样做。例如,如果您有两个 namespace 都包含同名类型,并且您想要使用两个 namespace 中的类型;在那种情况下,“使用”两个 namespace 可能会让人感到困惑。此外,“使用”使扩展方法发挥作用;如果存在您不想绑定(bind)到的扩展方法,请不要包含包含它们的命名空间。

if "Text" is nested inside "System" why only "using System" includes all the namespaces?

我不明白问题的措辞方式。我想你可能会问:

Why does using System; not make the simple name Text resolve to the nested namespace?

也就是说,为什么这不起作用:

namespace Foo
{
namespace Bar
{
class Blah {}
}
}

在不同的文件中:

using Foo;
class Abc : Bar.Blah {}

using Foo; 仅包括直接在 Foo 中声明的类型。它不会引入直接在 Foo 中声明的 namespace 。 C# 的设计者认为像这样将 namespace “纳入范围”太困惑了;人们通常使用 using 指令将类型“纳入范围”。

关于c# - 关于 C# 命名空间结构的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7516661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com