如何在c#中使用另一种形式的foreach获取list <string>值?

时间:2017-08-16 17:14:01

标签: c# arrays winforms list collections

我想使用zippedEdges.count() val anRdd = zippedEdges.map { case (a, b) => (SomeCaseClass(someMapBroadcast.value(a.someproperty), a.someotherproperty), b) }. join(someRdd, new HashPartitioner(partitions)).map(x => x._2).setName("rddName").persist(caching) anRdd.count() 循环

以另一种形式获取List<string>

ReportTestForm.cs

foreach

ReportFilterForm.cs

private void ReportTestForm_Load(object sender, EventArgs e)
{
    List<string> fieldList = new List<string>();

    fieldList.Add("Name");
    fieldList.Add("Class");
    fieldList.Add("Address");
    fieldList.Add("City");

    ReportFilterForm report = new ReportFilterForm(fieldList);
    report.Show(this);
}

抛出名为空引用异常

的异常

1 个答案:

答案 0 :(得分:3)

在调用InitializeComponent()方法之前,您似乎正在访问控件,该方法负责实例化控件,因此在该方法之前访问控件会导致 NRE(空引用异常),确保你先调用它,有多种可能的解决方案。以下是:

解决方案1:

在访问构造函数中的控件之前调用InitializeComponent()

public ReportFilterForm(List<string> fieldListFromReport)
{
    InitializeComponent(); // note this
    List<string> record = new List<string>(fieldListFromReport);

    foreach(string fields in record)
    {
        listBoxFieldNames.Items.Add(fields);
    }

}

解决方案2:

您可以使用this()调用无参数构造函数,因为通常构造函数包含对InitializeComponent方法的调用:

public ReportFilterForm(List<string> fieldListFromReport) 
         : this() // call parameterless constructor
{

    List<string> record = new List<string>(fieldListFromReport);

    foreach(string fields in record)
    {
        listBoxFieldNames.Items.Add(fields);
    }

}

解决方案3:

您可以在FormLoad事件中访问它,就像您在调用它的代码段中所做的那样:

public class ReportFilterForm
{
    List<string> _record;
    public ReportFilterForm(List<string> fieldListFromReport)
         : this()
    {
        _record = new List<string>(fieldListFromReport);
    }

    public ReportFilterForm()
    {
         InitializeComponent(); 
    }

    public void ReportFilterForm_Load(object sender, EventArgs e)
    {

      foreach(string fields in _record)
      {
         listBoxFieldNames.Items.Add(fields);
      }
   }

}