我相信我对命名空间层次结构有一个根本性的误解,导致了与这个问题几乎相反的问题:vb.net 系统命名空间与同级命名空间冲突
我有两个 .cs 文件,其中包含以下内容:
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出现错误: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://learn.microsoft.com/dotnet/csharp/language-reference/keywords/using-directive
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)