繁体   English   中英

C#中的绝对/外部和内部命名空间混淆

[英]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();
        }
    }
}

我该怎么解决这个问题? 只是在我的命名空间中移动using语句也无济于事。

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

global::Foo.Uber

您实际上可以通过根命名空间指定完整路径

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

命名空间概述

命名空间具有以下属性:

  • 他们组织大型代码项目。

  • 他们与。分开。 运营商。

  • using指令意味着您不需要为每个类指定命名空间的名称。

  • 全局命名空间是“根”命名空间: global :: system将始终引用.NET Framework命名空间System

我喜欢这个而不是别名,因为当你阅读它时,你确切地知道发生了什么。 如果跳过定义,别名很容易被误解。

别名为using语句中的命名空间:

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

您可以使用别名指令

using Outer = Foo.Uber;

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

使用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指令中指定别名。

暂无
暂无

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

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