我一直收到堆栈溢出异常。我已将其缩小到此类以尝试找出问题所在,但我根本不知道为什么我一直收到此错误消息?最初我在另一个类中有用户界面,但只是为了消除调用方法中的所有其他问题,我将要点移到了这个类中以尝试找出问题所在。我想这可能是我的属性(property)?也许这对其他人来说是显而易见的,但我就是不明白。
由于我是编程的新手,我希望能就我做错的地方提供一些帮助。 据我了解,当您遇到类似无限循环的情况时,就会出现此问题?
namespace MyNameSpace
{
public class Customers
{
private List<Customers> customers;
public Customers()
{
customers = new List<Customers>();
AddCustomer(new Customers()
{
Name = "A", Telephone="1"
});
}
public string Name
{
get;
set;
}
public string Telephone
{
get;
set;
}
public void RunTest()
{
Console.WriteLine();
Console.WriteLine("****** VIDEOSTORE ******");
Console.WriteLine();
Console.WriteLine("1. Show Customers");
Console.WriteLine("6. Quit");
string userChoice = Console.ReadLine();
switch (userChoice)
{
case "1":
View();
break;
break;
case "2":
break;
}
}
public void View()
{
foreach (Customers c in customers)
{
Console.WriteLine();
Console.WriteLine(c.Name);
Console.WriteLine(c.Telephone);
Console.WriteLine();
}
}
public void AddCustomer(Customers custom)
{
customers.Add(custom);
}
}
}
最佳答案
在 Customers 构造函数中,您再次调用 Customers 构造函数,创建无限递归。
对于客户列表和单个客户,您应该有一个单独的类:
namespace MyNameSpace
{
public class Customer
{
public string Name
{
get;
set;
}
public string Telephone
{
get;
set;
}
}
public class Customers
{
private List<Customer> customers;
public Customers()
{
customers = new List<Customer>();
AddCustomer(new Customer()
{
Name = "A", Telephone="1"
});
}
public void RunTest()
{
Console.WriteLine();
Console.WriteLine("****** VIDEOSTORE ******");
Console.WriteLine();
Console.WriteLine("1. Show Customers");
Console.WriteLine("6. Quit");
string userChoice = Console.ReadLine();
switch (userChoice)
{
case "1":
View();
break;
break;
case "2":
break;
}
}
public void View()
{
foreach (Customer c in customers)
{
Console.WriteLine();
Console.WriteLine(c.Name);
Console.WriteLine(c.Telephone);
Console.WriteLine();
}
}
public void AddCustomer(Customer customer)
{
customers.Add(customer);
}
}
}
关于c# - 堆栈溢出异常——为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8962443/