简体   繁体   English

当类和命名空间同名时区分类和命名空间

[英]Differentiating class and namespace when class and namespace have the same name

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            A.B var = new A.B();
        }
    }
}

Compiled with msvc 2019 and .net core 3.1, this code sample gives the following error:使用 msvc 2019 和 .net core 3.1 编译,此代码示例给出以下错误:

Error   CS0426  The type name 'B' does not exist in the type 'A'

I understand that it's better not to give the same names for classes and namespace.我知道最好不要为类和命名空间提供相同的名称。 But is there any way to workaround such collision?但是有没有办法解决这种碰撞?

There is no need to declare namespace as class B is already declared with the same namespace with class A .不需要声明命名空间,因为类B已经用与类A相同的命名空间声明了。 So just delete A and Visual Studio will figure out what it is desirable:因此,只需删除A ,Visual Studio 就会弄清楚它是可取的:

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            B var = new B();
        }
    }
}

UPDATE:更新:

An alternative solution is:另一种解决方案是:

using _a = A;

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            _a.B var = new _a.B();
        }
    }
}

You should avoid a scenario where you name your classes and namespaces the same.您应该避免将类和命名空间命名为相同的情况。 If you can't or using third party code, you can always refer to the namespace with the global:: keyword:如果您不能或使用第三方代码,您始终可以使用global::关键字引用命名空间:

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            global::A.B var = new global::A.B();
        }
    }
}

I think you are misunderstanding how namespaces work.我认为您误解了名称空间的工作原理。 You don't need to fully qualify B inside class A. You can simply refer to class B because both classes are in the same namespace.您不需要在类 A 中完全限定 B。您可以简单地引用类 B,因为两个类都在同一个命名空间中。 Like so:像这样:

namespace A
{
    class B
    {

    }

    class A
    {
        public void f()
        {
            B var = new B();
        }
    }
}

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

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