2013-02-25 64 views
0

我有下面的代码,并由于某种原因,我得到的错误:获得在C#代码意外“System.StackOverflowException”

An unhandled exception of type 'System.StackOverflowException' occurred in WpfApplication1.exe at the line : this.JointName = joint; inside the public Customer(String joint, String action)

当我运行的代码。

的Class1.cs代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace WpfApplication1 
{ 
    public class Customer 
    { 
     public String JointName { get; set; } 
     public String ActionName { get; set; } 
     public List<Customer> lst = new List<Customer>(); 

     public Customer(String joint, String action) 
     { 
      this.JointName = joint; 
      this.ActionName = action; 
      this.lst.Add(new Customer(this.JointName, this.ActionName)); 
     } 

     public List<Customer> GetList() 
     { 
      return this.lst; 
     } 
    } 
} 

MainWindow.xaml.cs代码:

namespace WpfApplication1 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    /// 

    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      Customer Data1 = new Customer("Joint1", "Action1"); 
      List<Customer> List = Data1.GetList(); 
      dataGrid1.ItemsSource = List; 

     } 
    } 
} 

你们可以看到我在做什么错在这里?我不知道在哪里我可以有一个无限循环..

+8

基本上,当你创建一个用户,把它添加到客户的内部列表中的新客户,这更增加了其内部列表中有一个新的客户,等等...... – 2013-02-25 19:18:18

+0

谢谢。我好蠢! – CarbonD1225 2013-02-25 19:20:57

+0

您反复initlaize的Cosntructor infinte次 – 2013-02-25 19:21:26

回答

0

的Class1.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace WpfApplication1 
{ 
    public class Customer 
    { 
     public String JointName { get; set; } 
     public String ActionName { get; set; } 


     public Customer(String joint, String action) 
     { 
      this.JointName = joint; 
      this.ActionName = action; 

     } 


    } 
} 

MainWindow.xaml.cs代码:

namespace WpfApplication1 
    { 
     /// <summary> 
     /// Interaction logic for MainWindow.xaml 
     /// </summary> 
     /// 

     public partial class MainWindow : Window 
     { 
      public MainWindow() 
      { 
       InitializeComponent(); 
       Customer Data1 = new Customer("Joint1", "Action1"); 
       List<Customer> list = new List<Customer>(); 
       list.add(Data1); 
       dataGrid1.ItemsSource = list; 

      } 
     } 
    } 
0

您反复调用Customer构造函数递归。所以,你的调用堆栈看起来是这样的:

Customer(String joint, String action) 
Customer(String joint, String action) 
Customer(String joint, String action) 
Customer(String joint, String action) 
Customer(String joint, String action) 
... 

每种方法等待完成后调用list.Add

只是碰巧拨打set属性JointName是打断堆栈帧的最后一个方法调用。

0

为客户构造包含调用本身上的最后一行:

this.lst.Add(新客户(this.JointName,this.ActionName))

也就是说源我们错误。

+0

展开你的答案。说出为什么会导致错误等等,以及它应该是什么。 – 2013-02-25 19:38:35

0

客户的构造始终执行“新客户”,然后调用客户的构造,等等,循环往复。