如何避免看似自动引用“父"命名空间? [英] How to avoid seemingly automatic reference of "parent" namespaces?

查看:83
本文介绍了如何避免看似自动引用“父"命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我对命名空间层次结构有一个根本的误解,导致几乎与这个问题相反的问题:vb.net 系统命名空间与兄弟命名空间冲突

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

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

I have two .cs files containing the below:

文件 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 - 命名空间Parent.Math"中不存在类型或命名空间名称Sqrt"

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

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.

谢谢.

推荐答案

当你在一个命名空间中时,编译器总是假设你也在父命名空间中.

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

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

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.

没有命名空间,你就在global中.

Without namespace, you are in 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

这篇关于如何避免看似自动引用“父"命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆