【问题标题】:Why is Root Namespace automatically included为什么自动包含根命名空间
【发布时间】:2018-07-08 01:35:04
【问题描述】:

我的一位同事刚刚遇到了一个奇怪的编译器怪癖,它正在导入看起来像“根”命名空间的东西。

问题在于,当我们添加对具有Root.Security 命名空间的共享库的引用时,它会在每个文件中抱怨使用了Root.Entity.X 类(即使它没有using Rootusing Root.Security.

例子

Root.Entities大会

Security.cs

namespace Root.Entities
{
    public class Security { } // Represents a Security in the sense of financial instrument
}

Root.Security大会

这个程序集有 Active Directory + Permission 共享助手,

SecurityHelper.cs

namespace Root.Security
{
    public class SecurityHelper { } // AD/Permission helper
}

Root.Gui大会

Main.cs

using Root.Entities;

namespace Root.Gui
{
    public class Main
    {
        public Main()
        {
            // The following causes an error 
            // if Root.Security is add as a reference to the project.
            // even without adding `using Root.Security`
            var security = new Security();
        }
    }
}

问题

我的问题是,为什么编译器会抛出错误并选择Security 作为命名空间,即使我们在任何地方都没有using Rootusing Root.Security!好像是自动在某处添加using Root

注意现在我们已经通过设置using SecurityEntity = Root.Entities.Security修复了它

【问题讨论】:

  • 为什么你有一个类被命名为另一个库的命名空间?那里出了点问题
  • @CamiloTerevinto 遗留代码,一个是完全独立于另一个创建的。 Security 库是为共享安全助手创建的,Security 实体代表财务安全,它们都被用于多个 (10-40) 项目中,但我猜直到现在才一起使用?
  • Root.GUI 位于命名空间 Root 下,因此会自动包含 Root。当您包含 Root.Entities 时,您在根级别有一个名为 Security 的类和一个名为 Security 的命名空间,导致冲突的原因是编译器不知道您是在引用命名空间还是类。
  • @Gusman,这就是我假设正在发生的事情,问题是为什么即使“默认”命名空间是 Root.Gui,它也会自动导入 Root。我会理解它包括Root.Gui,但不是它下面的所有其他命名空间!否则按照同样的思路,为什么using System.X 不会自动导入System 根命名空间?
  • @MichalCiechan 那是因为你的主命名空间在另一个命名空间下,与导入不同,这就是为什么导入System.XXX不会自动导入System,但是如果你在下面创建一些东西System.Whatever 然后System 将被自动包含在内。这里的想法是,如果您在另一个命名空间下创建一个新命名空间,是因为该根命名空间包含子命名空间所需的代码。

标签: c# .net compiler-errors compilation


【解决方案1】:

我无法解释“为什么?” - 我可以复制它,但有一些解决方法

选项 1:完全限定类型:

var security = new Root.Entities.Security();

选项 2:将您的 using 指令移入命名空间声明:

namespace Root.Gui
{
    using Root.Entities;
    public class Main
    {
        public Main()
        {
            // The following causes an error 
            // if Root.Security is add as a reference to the project.
            // even without adding `using Root.Security`
            var security = new Security();
        }
    }
}

using 别名方法没有修复它让我有点惊讶:

using Security = Root.Entities.Security;

但是你可以用选项 3 作弊:

using SecurityRenamed = Root.Entities.Security;
...
var security = new SecurityRenamed();

【讨论】:

  • 所以现在的问题是,选项 2、using inside namespace 或选项 3(是的,我们尝试了 using Security = 但失败了)。 Option1 实在是太丑了,因为它主要用作泛型参数,已经够迷糊了!
  • @MichalCiechan 我只是注意到您在问题的底部已经有了选项 3;所以......你的电话真的;我个人讨厌使用不在代码文件顶部的指令,但是:你的代码,不是我的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多