0

我有一个在 C# 中递归的函数,我想编辑一个在函数外部声明的全局变量(我假设它是全局的,因为它之前是公共的)。由于某种原因,我不知道它无法在该特定函数中看到公共变量。它可以在我的代码的第一个函数中看到它,但不能在我需要访问它并更改它以节省大量时间打开大量文件的第二个函数中...

有什么理由无法访问它吗?如果是这样,我怎么能绕过它?

提前非常感谢!

public int[] timeInfo = new int[2];
   private void ListDirectory(TreeView treeView, string path) 
        {     
            treeView.Nodes.Clear();   
            var rootDirectoryInfo = new DirectoryInfo(path);    
            treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo)); 
        }

   private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo) 

   {

       var directoryNode = new TreeNode(directoryInfo.Name);

       foreach (var directory in directoryInfo.GetDirectories())
            directoryNode.Nodes.Add(CreateDirectoryNode(directory));

       foreach (var file in directoryInfo.GetFiles())            
       {

           int check =0;                         
           try                
           {

               string s = "";                    
               s = directoryInfo.FullName + "\\" + file.Name;                    
               List<string> row, row2, row3 = new List<string>();

               using (StreamReader readFile = new StreamReader(s))
               {

                   row = (readFile.ReadLine().Split(',').ToList());
                   try 
                   {                           
                       row2 = (readFile.ReadLine().Split(',').ToList());
                       //timeInfo[0] = row2[0];
                   }
                   catch { check = 1; }
                   try
                   {
                       row3 = (readFile.ReadLine().Split(',').ToList());
                       //timeInfo[1] = row3[0];
                   }

                   catch { }
                }

                TreeNode[] headerNodes = new TreeNode[row.Count];

                for (int i = 0; i < row.Count; i++)
                {

                    headerNodes[i] = new TreeNode(row[i]);
                    if (check == 1)
                    {                       
                        headerNodes[i].BackColor = Color.Red;
                        headerNodes[i].ForeColor = Color.White;
                    }

                }
                directoryNode.Nodes.Add(new TreeNode(file.Name, headerNodes));
            }
            catch 
            {
                directoryNode.Nodes.Add(new TreeNode(file.Name));
            }
        }         
        return directoryNode; 
    }     
4

5 回答 5

6

第二个函数是静态的,变量只存在于对象的上下文中。

于 2012-05-17T19:05:37.423 回答
5

该方法是静态的。变量不是。您不能从静态方法中访问类的非静态(实例)成员。类中的公共变量不是全局变量。您必须将其设为 public static 以使其成为全局变量(我不建议使用全局变量),例如:

public static int[] timeInfo = new int[2];
于 2012-05-17T19:06:00.557 回答
3

您需要将其设为静态才能让您的静态函数看到它。

于 2012-05-17T19:06:05.567 回答
1

由于您的方法,您的变量必须是静态的。因为方法是静态的,所以只能看到静态变量。

于 2012-06-20T12:59:26.430 回答
1

您还需要将变量定义为静态:

public static int[] timeInfo = new int[2];
于 2012-05-17T19:07:07.967 回答