简体   繁体   English

全局名称空间优先于使用名称空间?

[英]Global namespace takes presidence over using namespace?

I feel like this is a silly question, but I can;t seem to figure out why this is happening. 我觉得这是一个愚蠢的问题,但我似乎无法弄清楚为什么会这样。 Consider the following: 考虑以下:

// file: A.cs
class A {
    public static string ns = "global";
}


// file: myNamespace\A.cs
namespace myNamespace {
    class A {
        public static string ns = "myNamespace";
    }
}


// in some other file...
using myNamespace;

class myClass {
    public void myMethod() {
        Console.WriteLine(A.ns);
    }
}

// OUTPUT: global

Now, since I have declared I want to use myNamespace; 现在,既然我已经声明了,我想使用myNamespace;。 why is the compiler stubbornly trying to use the global version instead of the namespaced version? 为什么编译器顽固地尝试使用全局版本而不是命名空间版本? What is the point of using if it is going to do this? 如果要这样做,使用的目的是什么?

My real code is more complicated than this of course. 我的真实代码当然比这还要复杂。 In the real code I am having the issue in (Unity API), I am getting a compile error in a case more like this: 在真实的代码中,我在(Unity API)中遇到问题,在类似这样的情况下,我收到编译错误:

A myObj = gameObject.GetComponent<A>();

This gives me an argument exception. 这给了我一个论点例外。 Not sure if maybe this has to do with generics? 不知道这是否与泛型有关? Am I missing something very dumb? 我想念一些很蠢的东西吗?

I can't test it or find the spec right now, but I believe the resolution rules will search the namespace that the calling code is in first. 我现在无法对其进行测试或找到规格,但我相信解析规则将搜索调用代码首先所在的名称空间。 Since your calling code is in the global namespace, that namespace is searched fist. 由于您的调用代码在全局名称空间中,因此将首先搜索该名称空间。 If you put the calling code inside the myNamespace namespace I suspect you'd get the behavior you are looking for. 如果将调用代码放在myNamespace命名空间中,我怀疑您会得到想要的行为。

If the calling code was not in either namespace then you should get an "ambiguous type" compiler error. 如果调用代码不在两个名称空间中,则应该收到“歧义类型”编译器错误。

Also note that your classes are internal by default, although if your classes are all in the same assembly that should be an issue. 还要注意,默认情况下您的类是internal类,尽管如果所有类都在同一程序集中,则应该是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM