我找不出爲什麼我得到這個錯誤。我正在爲我嘗試創建的對象設置一個實例。任何幫助將非常感激。我將發佈我的表單代碼,然後發佈下面的類代碼。該應用程序運行良好,當我點擊btnAdd
時,它只是給我那個空引用錯誤。C#System.NullReferenceException {「對象引用未設置爲對象的實例。」}
public partial class frmProperties : Form
{
Agent curAgent;
PropertyCollection pc;
int currRecord;
public frmProperties()
{
InitializeComponent();
}
public frmProperties(Agent ac, PropertyCollection pcPassed)
{
InitializeComponent();
curAgent = ac;
pc = pcPassed;
}
//check if there is a property in the list
private void frmProperties_Load(object sender, EventArgs e)
{
if (curAgent.AgentPropertyList.Count > 0)
ShowAll();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (currRecord < curAgent.AgentPropertyList.Count - 1)
{
currRecord++;
ShowAll();
}
else MessageBox.Show("No more properties to view");
}
void ShowAll()
{
txtId.Text = curAgent.AgentPropertyList[currRecord].ToString();
Property p = pc.FindProperty(curAgent.AgentPropertyList[currRecord]);
}
private void btnShowPrev_Click(object sender, EventArgs e)
{
if (currRecord > 0)
{
currRecord--;
ShowAll();
}
else MessageBox.Show("No more properties to view");
}
private void btnAdd_Click(object sender, EventArgs e)
{
pc.AddProperty(Convert.ToInt32(txtId.Text), txtAddress.Text, Convert.ToInt32(txtBedrooms.Text), txtType.Text, Convert.ToInt32(txtSqFt.Text), Convert.ToDouble(txtPrice.Text), txtAgent.Text);
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
下面是代碼的類,它的add函數是在創建:
public class PropertyCollection
{
// list of properties
List<Property> propertyList = new List<Property>();
public List<Property> PropertyList
{
get { return propertyList; }
set { propertyList = value; }
}
public void AddProperty(int id, string address, int bedrooms, string type, int sqft, double price,string agent)
{
Property p = new Property(id,address,bedrooms,type,sqft,price,agent);
propertyList.Add(p);
}
public void RemoveProperty(int id)
{
Property rem = new Property(id);
propertyList.Remove(rem);
}
//loop through and find equivalent
public Property FindProperty(int id)
{
Property find = new Property(id);
for (int i = 0; i < propertyList.Count; i++)
if (propertyList[i].Equals(find))
return propertyList[i];
return null;
}
//Count property and INDEXER
public int Count
{
get { return propertyList.Count; }
}
public Property this[int i]
{
get { return propertyList[i]; }
set { propertyList[i] = value; }
}
}
你有兩個構造函數,一個是空的,一個是args,空的調用是args。然後檢查pcPassed是否爲空,如果是,則初始化它的一個新實例。 – Sorceri
因此,當你在斷開的線上放置一個斷點並檢查了變量時,哪一個爲空? –
由於Sorceri概述的原因,「pc」並不總是被初始化。 – Chris