【问题标题】:Namespaces in C# Same ProjectC# 同一项目中的命名空间
【发布时间】:2012-10-17 16:50:35
【问题描述】:

我有一个像这样的静态类:

namespace Engine.Configuration
{
    public static class Configuration
    {
        public static int i;
    }
} 

在同一个项目中,但在不同的命名空间中,我有一个类试图访问静态类变量:

namespace Engine.MainProgram
{
    public class MainProgram
    {
        int x;
        int y;
        public void LoadConfiguration()
        {
            x = Configuration.Configuration.i;
        }
    }
}

我想做的只是在 MainProgram 中放置一个 using 语句,如下所示:

using Engine.Configuration;
...
x = Configuration.i;

但是当我尝试使用 Visual Studio 时,总是将 Configuration 视为命名空间而不是静态类。我的问题是为什么会发生这种情况,我该如何纠正?

【问题讨论】:

  • 一种方法:using Configuration = Engine.Configuration.Configuration; .. x = Configuration.i;。虽然我建议保持命名空间和类型名称的唯一性。
  • 你的类名和命名空间名是一样的..这是模棱两可的..你应该避免设置相同的名字!

标签: c# namespaces


【解决方案1】:

试试:

using A = Engine.Configuration;

然后

x = A.Configuration.i;

或者直接使用

x = global::Engine.Configuration.Configuration.i

【讨论】:

    【解决方案2】:

    编译器并不总是知道如何区分命名空间和同名的类名。

    改变这个:

    using Engine.Configuration;
    

    namespace alias

    using Configuration = Engine.Configuration.Configuration;
    

    解释:

    假设您直接在根命名空间 Engine 下工作,如下所示:

    namespace Engine
    {
    }
    

    然后你可以像这样在其他命名空间中获取东西:

    namespace Engine
    {
        Engine.Configuration.Configuration;
    
        // Or since you are in the root (Engine) you don't need to specify Engine:
        // You can always omit the root namespace if the namespace you're in has the same root.
        Configuration.Configuration;
    }
    

    或者通过为命名空间声明一个 using,但编译器不会知道你是指命名空间还是命名空间中的类:

    using Engine.Configuration;
    
    namespace Engine
    {
        // This will still work.
        Engine.Configuration.Configuration;
    
        // This will break, do we mean "Engine.Configuration.Configuration" or "Engine.Configuration"?
        Configuration;
    }
    

    因此,一个类的名称永远不要与其所在的命名空间相同。也许将命名空间更改为 Engine.Configurations

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 2016-08-29
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多