简体   繁体   中英

Absolute/outer and inner namespace confusion in C#

using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}

How could I solve this? Just moving the using statement inside my namespace doesn't help.

您可以使用命名空间别名限定符 (通常为global::来引用默认/根命名空间:

global::Foo.Uber

You can actually specify the full path via the root namespace

var x = global::Foo.Uber.Bar();

Namespaces Overview

A namespace has the following properties:

  • They organize large code projects.

  • They are delimited with the . operator.

  • The using directive means you do not need to specify the name of the namespace for every class.

  • The global namespace is the "root" namespace: global::system will always refer to the .NET Framework namespace System .

I prefer this over aliases because when you read it, you know exactly what is going on. Aliases can be easy to misunderstand if you skip over the definition.

Alias the namespace in the using statement:

using ThatOuterFoo = Foo.Uber;
...
...
//Some time later...
var x = ThatOuterFoo.Bar();

You can use using alias directives

using Outer = Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){                
            var x = new Outer.Bar(); //outer class
        }
    }
}

Using Aliaseseseseseses

using Foo.Uber;
using FooUberBar = Foo.Uber.Bar

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = FooUberBar();
        }
    }
}

您可以在MSDN中描述的using指令中指定别名。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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