C#:从外部作用域访问内部作用域中的变量

问题描述:

我正在 while 循环中创建一个类的实例 - 我需要 while 循环来获取创建实例所需的输入参数(我必须从 extern 文件中读取它).但是我想从循环外部访问实例.有没有可能?

I'm creating an instance of a class inside a while loop - I need the while loop to get the input arguments i need to create the instance (I have to read it in from an extern file). But then I would like to have access to the instance from outside the loop. Is there a possibility?

public static <class> leseProjektDatei()
{

while ((zeile = datei.ReadLine()) != null)
       {
           Debug.WriteLine(zeile);
           string id, wetterdatei, fruchtfolge, bodenprofil, grundwasser;
           id = zeile.Substring(0, 5);
           wetterdatei = zeile.Substring(7, 14);
           fruchtfolge = zeile.Substring(22, 14);
           bodenprofil = zeile.Substring(37, 14);


           <class> projekt = new <class>(id, wetterdatei, fruchtfolge, bodenprofil);

            } 
 return <class>
}

是的,这样做:

public class Project{
    public string id{get;set;} 
    public string wetterdatei{get;set;}
    public string fruchtfolge {get;set;} 
    public string bodenprofil {get;set;} 
}


public static Project leseProjektDatei(){
Project projekt = new Project();
while ((zeile = datei.ReadLine()) != null)
       {
           projekt.id = zeile.Substring(0, 5);
           projekt.wetterdatei = zeile.Substring(7, 14);
           projekt.fruchtfolge = zeile.Substring(22, 14);
           projekt.bodenprofil = zeile.Substring(37, 14);

             } 
return projekt;
}

随便给班级起个名字.