How to avoid seemingly automatic reference of “parent” namespaces?

只谈情不闲聊 提交于 2021-01-27 13:23:57

问题


I believe I have a fundamental misunderstanding of namespace hierarchy, causing almost the opposite problem to this question: vb.net System namespace conflict with sibling namespace

I have two .cs files containing the below:

File 1

namespace Parent.Math
{
    public class Foo { }
}

File 2

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

File 2 presents the error: CS0234 - The type or namespace name 'Sqrt' does not exist in the namespace 'Parent.Math'

Why does the compiler assume Math to be reference to the sibling namespace and not the member of the explicitly referenced System namespace? The behavior is as if parent namespaces are automatically referenced. Is this correct? I would of at least expected an ambiguity error.

Thank you.


回答1:


When you are in a namespace, the compiler always assume that you are in the parent namespace too.

Hence while being in Parent.Child, writing Math, the compiler search in Child and next in Parent and found Math as a namespace but no Sqrt type, so the error.

The compiler search like that and go up the chain of namespaces.

Without namespace, you are in global.

You can simply write:

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

Or that in case of problem:

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

You can also write:

using SystemMath = System.Math;

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

And since C# 6:

using static System.Math;

Console.WriteLine(Sqrt(4));

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



来源:https://stackoverflow.com/questions/63878918/how-to-avoid-seemingly-automatic-reference-of-parent-namespaces

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