C#:从外部作用域访问内部作用域中的变量 [英] C#: access variable in the inner scope from the outer scope

查看:43
本文介绍了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;
}

随便给班级起个名字.

这篇关于C#:从外部作用域访问内部作用域中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆