我在C#中编写了一个bubblesort并遇到了这个问题。以下是我的课程,课程结束后我将描述我的问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BubbleSort
{
class Person
{
public String FirstName { get; set; }
public String LastName {get; set;}
public String PhoneNumber { get; set; }
public Person(String firstName, String lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace BubbleSort
{
class ListProvider
{
//Class Variables
private StreamReader fileReader;
//private List<Person> test;
#region Properties
public List<Person> TheList
{
get { return TheList; }
set { TheList = value; }
}
#endregion
/// <summary>
/// I wish C# had a Scanner class :/. How different are these languages really?
/// </summary>
/// <param name="fileName"></param>
public ListProvider(string fileName)
{
// test = new List<Person>();
using (fileReader = new StreamReader(fileName))
{
String line = "";
while (fileReader.Peek() != -1)
{
line = fileReader.ReadLine();
String[] nameArray = line.Split(' ');
TheList.Add(new Person(nameArray[0], nameArray[1]));
//test.Add(new Person(nameArray[0], nameArray[1]));
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
ListProvider listProvider = new ListProvider("C:\\Users\\JC Boss\\Desktop\\Career\\Programming Practice\\BubbleSort\\BubbleSort\\names.txt");
foreach (Person person in listProvider.TheList)
{
Console.WriteLine(person.FirstName + " " + person.LastName);
}
}
好。因此,当我尝试向此列表添加一个新Person时,我得到一个堆栈溢出异常。现在,如果我要取消注释List变量测试,并添加到那个。它会工作正常,并不会抛出任何错误。为什么会这样?我环顾四周但却看不出为什么会发生财产? } }
答案 0 :(得分:1)
public List<Person> TheList
{
get { return TheList; }
set { TheList = value; }
}
这个setter指的是它自己。任何读取或写入它的尝试都将导致无限递归。