【问题标题】:How to access nested namespaces to avoid the need to fully qualify in .NET如何访问嵌套命名空间以避免在 .NET 中完全限定
【发布时间】:2019-09-26 09:28:39
【问题描述】:

我觉得我在这里遗漏了一些明显的东西,但是这个问题已经困扰了我一段时间。

我在几个不同的嵌套命名空间中定义了一些类:

namespace Awesome.Example {

    namespace V1 {
        public class PopTart {
            public bool PoppinUp {get; set;}
            public bool Hot {get; set;}
        }
    }

    namespace V2 {
        public class PopTart {
            public bool PoppinUp {get; set;}
            public bool SoCool {get; set;}
            public bool AreHot {get; set;}
        }
    }

}

但如果我尝试使用包含来简化声明,IDE (VS) 会抱怨我需要完全限定类。

例如:

using Awesome.Example;

public class Main {

    public V1.PopTart Strawberry {get; set;}
    public V2.PopTart Blueberry  {get; set;}

}

这会产生两个错误:

The type or namespace name 'V1' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'V2' could not be found (are you missing a using directive or an assembly reference?)

我不明白这是为什么。谁能解释如何完成我所追求的?

【问题讨论】:

  • 请指定属性名:publicV1.PopTart PROPERTY_NAME {get; set;}
  • 你不能那样做。如果在Awesome.Example 中定义了Main,或者Awesome 中的Main 可以声明public Example.V1.PopTart A { get; set; },则像V1.PopTart 这样的部分命名空间将起作用。但是Main 必须与这些类有一些共同的“祖先”命名空间。否则,它必须全有或全无。这可能是为了使名称解析更易于管理。
  • 谢谢你,这大大澄清了事情。我不知道共同祖先是必要的。我以为提供“使用”就足够了。

标签: c# .net namespaces


【解决方案1】:

尝试像这样使用命名空间别名:

using V1 = Awesome.Example.V1;
using V2 = Awesome.Example.V2;

public class Main
{
    public V1.PopTart p1 { get; set; }
    public V2.PopTart p2 { get; set; }

}

或者像这样完全限定你的命名空间:

public class Main
{
    public Awesome.Example.V1.PopTart p1 { get; set; }
    public Awesome.Example.V2.PopTart p2 { get; set; }
}

更多解释和示例请参考以下问题:Nested namespaces

【讨论】:

  • 您链接到的问题的出色总结。没有出现在我的搜索中。
【解决方案2】:

尝试使用完整的命名空间和嵌套命名空间,比如

public class Main
{
    public Awesome.Example.V1.PopTart var1{get; set;}
    public Awesome.Example.V2.PopTart var2{get; set;}
}

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2018-02-03
    • 1970-01-01
    • 2017-08-09
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多