2013-02-25 72 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

客戶的構造始終執行「新客戶」,然後調用客戶的構造,等等,循環往復。