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

C# 类型为';的未处理异常;System.StackOverflowException';在application.exe中,c#,sql-server,C#,Sql Server,当我尝试连接到数据库时出现此错误。有人知道如何修复此错误吗 欢迎任何类型的反馈。多谢各位 这是在我的DBConnection类中 namespace A.B.BesmonteDentalClinic { class DBConnection { SqlConnection connection; int flag = 0; public int Flag { get { return fl

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

欢迎任何类型的反馈。多谢各位

这是在我的
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 Load上的代码

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();
    }                
}

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

这里的问题是您的连接属性正在调用自身。当您的消费者调用它时,该属性将无限地继续调用自己,直到堆栈溢出为止

将类更改为使用.NET的自动属性(不需要备份字段)。 有关自动特性的详细信息,请参见:


您的
连接
属性尝试访问自身以获取值,而不是备份字段。请注意,这看起来很可疑,好像您正计划在周围共享
SqlConnection
对象。这通常也是问题的原因。有些离题,但
SqlConnection
SqlCommand
,和
SqlDataReader
都实现了
IDisposable
,因此,它们都应该包装在一个语句中。这是调试时应该立即显而易见的事情之一…从代码中删除客户端名称是一个好主意在DbConnection上实现IDisposable是一个好主意,因为它包含SqlConnection,所以应该处理它。感谢您的回答。但在从类调用连接时,这似乎不是正确的代码。你能建议什么是正确的代码吗?谢谢你,蒙卡达!
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);
        }
    }
}