【问题标题】:Accessing global class of same name inside another namespace在另一个命名空间中访问同名的全局类
【发布时间】:2023-04-01 11:05:01
【问题描述】:

在我的项目中,我有一个静态类 Const.cs 用于存储 Const 变量。 例如。

public static class Const
{
  public const string EXAMPLE= "Example";
  .........
  .........
  // blah blah..
}

它是一个全局文件,不属于任何命名空间。由于某些特定要求,我必须创建另一个具有同名“Const”的 Const 类,但这次是在其他命名空间下(比如 Namespace1.Class1.cs

public class Namespace1.Class1
{
  string test = Const.EXAMPLE;  // this line throws error by compiler

  public static class Const
  {
    ......
    ......
  }
}

问题是:我在 Namespace1.Class1.cs 中使用 Const.strExample 常量

所以存在歧义问题。编译器无法识别 Const.strExample,因为我在 Namespace1.Class1.cs 中声明了第二个 Const 类。 有没有办法以某种方式解决这个问题并保留相同的名称,或者我不能这样做?

请指教。

【问题讨论】:

    标签: c# namespaces


    【解决方案1】:

    您可以使用global 命名空间,如下所示。

    namespace Namespace1
    {
        public class Class1
        {
          string test = global::Const.EXAMPLE;
          string test2 = Namespace1.Class1.Const.EXAMPLE;
    
          public static class Const
          {
            ......
            ......
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-06
      • 1970-01-01
      • 2012-05-11
      • 2011-01-15
      • 2021-01-02
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多