StackOverFlow on Application start point
I built a program, and i press a button, the program crashes. Here is the button's code:
_alRecord.WriteXml(@".\alRecord.xml", XmlWriteMode.WriteSchema);
Debuging returned StackoverFlow(location is marked in a comment), Here is the whole code:
private string alFile = @".\alRecord.xml";
public DataTable alRecord;
public DataTable _alRecord
{
get
{ //location of stackoverflow
if (_alRecord == null)
{
alRecord = new DataTable();
if (File.Exists(alFile))
{ _alRecord.ReadXml(alFile); }
else
{ InitDataTable2(_alRecord); }
}
return _alRecord;
}
}
private void InitDataTable2(DataTable table)
{
table.TableName = "AlTable";
table.Columns.Add("ID", typeof(int));
table.Columns.Add("sun", typeof(bool));
table.Columns.Add("mon", typeof(bool));
table.Columns.Add("tue", typeo开发者_StackOverflowf(bool));
table.Columns.Add("wed", typeof(bool));
table.Columns.Add("thu", typeof(bool));
table.Columns.Add("fri", typeof(bool));
table.Columns.Add("sat", typeof(bool));
table.Columns.Add("doors", typeof(string));
table.Columns.Add("from1", typeof(DateTime));
table.Columns.Add("to1", typeof(DateTime));
table.Columns.Add("from2", typeof(DateTime));
table.Columns.Add("to1", typeof(DateTime));
for (int i = 0; i < 99; i++)
{
var row = alRecord.NewRow();
row["ID"] = i;
row["sun"] = false;
row["mon"] = false;
row["tue"] = false;
row["wed"] = false;
row["thu"] = false;
row["fri"] = false;
row["sat"] = false;
row["doors"] = "";
row["from1"] = "00:01";
row["to1"] = "23:59";
row["from2"] = "00:01";
row["to2"] = "23:59";
alRecord.Rows.Add(row);
}
}
private void alSave_Click(object sender, EventArgs e)
{
_alRecord.WriteXml(@".\alRecord.xml", XmlWriteMode.WriteSchema);
}
You are calling your property from inside the getter of your property:
public DataTable _alRecord
{
get
{
if (_alRecord == null) // <= whoops
That causes an infinite recursion - calling the getter of the property to see if it returns null calls the getter of the property to see if it returns null calls the getter of the property...
@Dave makes a good point in the comments - in c# it is common to use a naming convention that your property is CasedLikeThis
and the backing field (the field where the property actually stores its value is _namedLikeThis
. It makes it easier to distinguish - you always know the _ means backing field, and vice versa.
精彩评论