为什么这个Application对象没有实例化?每当我运行代码时它都为null。
public class Applicant
{
private Application oApplication = new Application();
public Applicant()
{
oApplication = new Application();
}
public Application Application
{
get { return oApplication; }
set { oApplication = value; }
}
}
这是应用程序类
public class Application
{
public string ApplicationID { get; set; }
public ContactDetails ContactDetails { get; set; }
}
这是调用代码......
public Applicant[] GetApplicants()
{
Applicant[] oApplicant;
DataSet dsExcelSchema = new DataSet();
dsExcelSchema = GetDataAsDataSet();
DataTable contactInfoTable = dsExcelSchema.Tables["ContactInformation$"];
int numOfApplications = contactInfoTable.Rows.Count - 1;
int i = 0;
oApplicant = new Applicant[numOfApplications];
foreach (DataRow dr in contactInfoTable.Rows)
{
Application oApplication = new Application();
oApplicant[i].Application.ApplicationID = dr["ApplicationID"].ToString();
i++;
}
return oApplicant;
}
它给我一个NullReferenceException。
答案 0 :(得分:5)
您忘记在数组元素中创建申请人的实例 - 应该这样做:
foreach (DataRow dr in contactInfoTable.Rows)
{
oApplicant[i] = new Applicant();
oApplicant[i].Application.ApplicationID = dr["ApplicationID"].ToString();
i++;
}
答案 1 :(得分:3)
创建对象数组时:
oApplicant = new Applicant[numOfApplications];
将填充nulls
。因此,您需要首先使用实际值初始化它:
for (int i = 0; i < numOfApplications; i++)
{
oApplicant[i] = new Applicant();
}
答案 2 :(得分:1)
除了其他答案之外,您还需要将numOfApplications设置为contactInfoTable.Rows.Count,而不是contactInfoTable.Rows.Count - 1;
int numOfApplications = contactInfoTable.Rows.Count;