C# 声明要在其他地方使用的变量

C# 声明要在其他地方使用的变量,c#,C#,我有以下代码: private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string Elementsfile; if (File.Exists(Application.StartupPath + "\\checkfiles.lst")) { string path = Application.StartupPath + "\

我有以下代码:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        string Elementsfile;
        if (File.Exists(Application.StartupPath + "\\checkfiles.lst"))
        {
            string path = Application.StartupPath + "\\checkfiles.lst";

            // Open the file to read from.
            foreach (string readText in File.ReadLines(path))
            {
                var elements = readText.Split('|');
                Elementsfile = elements[0];
                string HashString = elements[1];
                string ByteSize = elements[2];
                Console.WriteLine(Elementsfile + HashString + ByteSize);
            }
        }

        string filePath = Elementsfile;
}
我试图声明这些变量:

string Elementsfile = elements[0];
string HashString = elements[1];
string ByteSize = elements[2];
…并在类中的其他位置使用它们

当我尝试使用它们时,例如:string filePath=Elementfile;,我得到了错误


使用未分配的局部变量“ElementsFile”

您应该将它们作为类的字段,而不是局部变量。或者,您应该使它们至少在foreach循环的范围之外声明,以便在同一方法的其他代码块中访问它们

您必须在更广泛的范围内定义它们,尤其是在实例级别

class X {
   string ElementsFile;
   string HashString;

   void method(){
        ElementsFile = "file.txt"; // notice how you just assign the values 
        HashString = "something";  // instead of redefining them as string
   }
}
现在,类中的每个非静态方法都可以使用这些变量。如果您在方法内部重新定义它们,那么这也是有效的,但它会隐藏在实例级别上定义的变量

class X {
   string ElementsFile;
   string HashString;

   void method(){
        ElementsFile = "file.txt"; // notice how you just assign the values 
        HashString = "something";  // instead of redefining them as string
   }
}
在您的示例中,您是在foreach块中定义它们。这是比实例和方法范围更深的另一个层次。如果您只想在同一方法内但在foreach外重复使用这些变量,那么您可以为该场景调整相同的逻辑:

class X {  
   void method(){
        string ElementsFile;
        string HashString;

        foreach(something) {
            ElementsFile = "file.txt"; 
            HashString = "something";  
        }

        // Use the variables here
   }
}

c具有块作用域。这意味着变量仅在其定义的块内可见

因此,您应该在正确的级别定义它们:

public class MyClass
{
    string myClassVar; // this one is usable throughout the class

    void MyMethod()
    {
        string myMethodVar; // This one is visible inside this method
        string path = Application.StartupPath + "\\checkfiles.lst";

        // Open the file to read from.
        foreach (string readText in File.ReadLines(path))
        {
            var elements = readText.Split('|');
            string Elementsfile = elements[0];    // these ones are visible inside the for loop
            string HashString = elements[1];
            string ByteSize = elements[2];
            Console.WriteLine(Elementsfile + HashString + ByteSize);
        }
     }
}

要回答您的问题,您应该在方法之外或至少在for循环之外定义变量。请注意,如果执行foreach,则只保存循环写入的最后一个值,因为每次迭代都会覆盖这些值。

其他问题通常是正确的,但它们忽略了代码中的一个潜在错误。当您在各行中循环并修改变量时,每次都会覆盖上一个值。因此,一旦循环完成,您将只拥有最后一行的值。您可能希望执行类似的操作,将文件解析为列表:

public class HashEntryModel { //name it whatever represents a single line in your file
  public string ElementsFile { get;set;}
  public string Hash { get;set;}
  public string ByteSize { get;set;} //sounds like an integer?  Perhaps instead of string declare as int and parse with int.TryParse?
}

public class SomeClass()
{
 public List<HashEntryModel> HashEntries {get;set;}

 public SomeClass(){
   HashEntries = new List<HashEntryModel>();
 }

 public void SomeMethod() 
 {
  string path = Application.StartupPath + "\\checkfiles.lst";

  // Open the file to read from.
  foreach (string readText in File.ReadLines(path))
  {
    var elements = readText.Split('|');
    HashEntryModel current = new HashEntryModel();
    current.ElementsFile = elements[0];
    current.Hash = elements[1];
    current.ByteSize = elements[2];

    HashEntries.Add(current);//add the entry we just parsed to the list
  }

  //now anywhere in this class we can loop through the entries:

  foreach(HashEntryModel item in HashEntries)
  {
    Console.WriteLine(item.ElementsFile + item.Hash + item.ByteSize);
  }

 }

}

在您的示例中,您在foreach之后使用string ElementsFile,我试图在foreach之后和if语句外部使用它。@hulu804:if语句也被视为单独的上下文。在仍然允许您在两种上下文中使用的最低级别上声明变量ElementsFile。如果您无法理解:请编辑您的帖子,这样我就可以看到您的情况。@Hulu8004您的示例不显示此场景没有If,但假设您有If…{..foreach…{…ElementsFile=…},然后使用Jeroen在第二个示例中使用的相同技术,将变量的声明移动到if:string ElementsFile;…if…{..foreach…{…ElementsFile=…}上方Console.WriteLink可以访问相同的作用域:+ElementsFile;如果您搜索变量scope c,您可以找到一些示例和解释来帮助您更好地理解。@HULU804:将string ElementsFile;更改为string ElementsFile=null;。如果If语句从未执行,它将永远不会为ElementsFile赋值,这将在执行时导致问题您正在将ElementsFile的值分配给filePath。