在C#代码中获得意外的'System.StackOverflowException'

时间:2013-02-25 19:17:02

标签: c#

我有以下代码,由于某些原因我收到错误:

  

未处理的类型' System.StackOverflowException'   发生在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;

        }
    }
}

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

4 个答案:

答案 0 :(得分: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的{​​{1}}属性的调用才是打破堆栈帧的最终方法调用。

答案 1 :(得分:0)

Customer的构造函数包含对最后一行的调用:

this.lst.Add(new Customer(this.JointName,this.ActionName))

这是我们错误的来源。

答案 2 :(得分:0)

Customer的构造函数始终执行“new Customer”,然后无限制地调用Customer的构造函数。

答案 3 :(得分: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;

            }
        }
    }