application.exe中类型为'System.StackOverflowException'的未处理异常

时间:2019-02-01 15:36:33

标签: c# sql-server

当我尝试连接到数据库时出现此错误。有人知道如何解决此错误吗?

enter image description here

感谢任何类型的反馈。谢谢

这是在我的DBConnection班上

namespace A.B.BesmonteDentalClinic
{
    class DBConnection
    {
        SqlConnection connection;
        int flag = 0;

        public int Flag
        {
            get { return flag; }
        }

        public SqlConnection Connection
        {
            get { return this.Connection; }
        }

        public DBConnection()
        {
            this.connection = new SqlConnection("Data Source=DESKTOP-J3KOF5O;Initial Catalog=besmontedental;Integrated Security=True");

            try
            {
                this.connection.Open();
                flag = 1;
            }
            catch (Exception e)
            {
                flag = 0;
                MessageBox.Show(e.Message);
            }
        }
    }
}

这是Form1加载上的代码

var con = new DBConnection();

try
{
    SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM accounts ORDER BY id desc;", con.Connection);
    SqlDataReader rd = cmd.ExecuteReader();

    if (rd.HasRows)
    {
        rd.Read();
        int id = rd.GetInt32(0) + 1;
        txtID.Text = id.ToString();
    }                
}

1 个答案:

答案 0 :(得分:2)

这是为了回答您的StackOverflowException问题。请注意,您的代码中还有其他问题可以在StackExchange CodeReview中解决。 https://codereview.stackexchange.com/

这里的问题是您的 Connection属性正在自我调用。当您的使用者调用它时,该属性将无限地继续对其自身进行调用,直到其Stack溢出为止。

更改类以使用.NET的自动属性(无需后备字段)。 有关自动属性的更多信息,请参见:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

class DBConnection
{
    public int Flag { get; private set; }

    public SqlConnection Connection { get; private set; }

    public DBConnection()
    {
        Connection = new SqlConnection("Data Source=DESKTOP-J3KOF5O;Initial Catalog=besmontedental;Integrated Security=True");

        try
        {
            Connection.Open();
            Flag = 1;
        }
        catch (Exception e)
        {
            Flag = 0;

            MessageBox.Show(e.Message);
        }
    }
}
相关问题