【问题标题】:Not scoping static vars properly in C#在 C# 中没有正确地确定静态变量的范围
【发布时间】:2017-09-10 18:39:35
【问题描述】:

我是 C# 新手——这几乎是我的第一个程序。我正在尝试创建一些公共静态变量和常量以在程序中的任何位置使用。我尝试过的错误方法是将它们声明在同一命名空间中的单独类中,但它们与主程序的上下文无关。这是一个 WPF 应用程序。代码如下所示:

namespace testXyz
{
    class PublicVars
    {
        public const int BuffOneLength = 10000;
        public static int[] Buff1 = new int[BuffOneLength];

        public const int BuffTwoLength = 2500;
        public static int[] Buff2 = new int[BuffTwoLength];

        private void fillBuff1()
        {
            Buff1[0] = 8;
            Buff1[1] = 3;           
            //etc
        }

        private void fillBuff2()
        {
            Buff2[0] = 5;
            Buff2[1] = 7;           
            //etc
        }   
    }
}

第二个文件:

namespace testXyz
{
    public partial class MainWindow : Window
    {
        public MainWindow() 
        {
            InitializeComponent();
        }

        public static int isInContext = 0;
        int jjj = 0, mmm = 0;

        private void doSomething()
        {
            isInContext = 5;    // this compiles
            if (jjj < BuffOneLength)    // "the name 'BuffOneLength' does not exist in the current context"
            {
                mmm = Buff2[0]; // "the name 'Buff2' does not exist in the current context"
            }
        }
    }
}

当然,我的实际程序要长得多。我完全按照所示创建了上面的 WPF 应用程序来测试这个问题,我得到了这些错误,也发生在实际程序中。我真的不想在主程序中填充数组,因为它们很长,并且意味着很多滚动。我还希望有一个地方可以声明某些公共静态变量。这样做的正确方法是什么?

【问题讨论】:

  • 我不明白你为什么要两次声明同一个命名空间?
  • 这 2 个块在项目的 2 个不同的 .cs 文件中。 Visual Studio 生成命名空间声明。我在上面的示例中附加了它们。
  • 好的!没有在任何地方阅读它,所以假设它在同一个文件中。

标签: c# wpf


【解决方案1】:

您必须指定

// BuffOneLength from PublicVars class
if (jjj < PublicVars.BuffOneLength)  {
  ...
  // Buff2 from PublicVars class 
  mmm = PublicVars.Buff2[0];

或输入using static:

// When class is not specified, try PublicVars class
using static testXyz.PublicVars;

namespace testXyz {
  public partial class MainWindow : Window {
    ...

    // BuffOneLength - class is not specified, PublicVars will be tried  
    if (jjj < BuffOneLength) {
      mmm = Buff2[0]; 

【讨论】:

    【解决方案2】:

    您不能通过调用变量来访问另一个类中的静态变量。你需要先通过包含它的类,在你的情况下它会是

    PublicVars.BuffOneLength
    

    PublicVars.Buff2[0]
    

    【讨论】:

    • 谢谢。这就回答了。我将在变量前面加上类名。 “使用静态”将是一个不错的选择,但我只有 VS 2013...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多