如何避免看似自动引用 "parent" 名称空间?

How to avoid seemingly automatic reference of "parent" namespaces?

我相信我对命名空间层次结构有根本性的误解,导致了与这个问题几乎相反的问题:vb.net System namespace conflict with sibling namespace

我有两个包含以下内容的 .cs 文件:

文件 1

namespace Parent.Math
{
    public class Foo { }
}

文件 2

using System;
namespace Parent.Child
{
    public class Bar
    {
        public Bar()
        {
            Console.WriteLine(Math.Sqrt(4));           
        }
    }
}

文件 2 出现错误:CS0234 - The type or namespace name 'Sqrt' does not exist in the namespace 'Parent.Math'

为什么编译器假定 Math 是对兄弟名称空间的引用,而不是显式引用的 System 名称空间的成员?该行为就像自动引用父命名空间一样。这个对吗?我至少会预料到会出现歧义错误。

谢谢。

当您在命名空间中时,编译器始终假定您也在父命名空间中。

因此,在 Parent.Child 中写入 Math 时,编译器在 Child 中搜索,然后在 Parent 中搜索,并发现 Math 作为命名空间,但是没有Sqrt类型,所以报错。

编译器像那样搜索并沿着命名空间链向上移动。

没有命名空间,您在 global.

你可以简单地写:

Console.WriteLine(System.Math.Sqrt(4));           

或者出现问题时:

Console.WriteLine(global::System.Math.Sqrt(4));

你也可以这样写:

using SystemMath = System.Math;

Console.WriteLine(SystemMath.Sqrt(4));

从 C# 6 开始:

using static System.Math;

Console.WriteLine(Sqrt(4));

https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/using-directive