变量应该在函数内还是在函数外声明

本文关键字:函数 声明 变量 | 更新日期: 2023-09-27 18:15:42

这是很好的做法:-变量是否应该在函数内或函数外声明?

。1 .

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void btnLoad_Click(object sender, EventArgs e)
            {
                LoadData();
            }
            private void LoadData()
            {
**private SqlDataAdapter da;
            private SqlConnection conn;
            BindingSource bsource = new BindingSource();
            DataSet ds = null;
            string sql;**
    string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" + "Integrated Security=SSPI;";
                conn = new SqlConnection(connectionString);
    sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," + "ShipName, ShipCountry FROM Orders";
                da = new SqlDataAdapter(sql, conn);
                conn.Open();
                ds = new DataSet();
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);          
                da.Fill(ds, "Orders");
                bsource.DataSource = ds.Tables["Orders"];
                dgv.DataSource = bsource;          
            }
        }

。2。

public partial class Form1 : Form
        {
            **private SqlDataAdapter da;
            private SqlConnection conn;
            BindingSource bsource = new BindingSource();
            DataSet ds = null;
            string sql;**
            public Form1()
            {
                InitializeComponent();
            }
            private void btnLoad_Click(object sender, EventArgs e)
            {
                LoadData();
            }
            private void LoadData()
            {
    string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" + "Integrated Security=SSPI;";
                conn = new SqlConnection(connectionString);
    sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," + "ShipName, ShipCountry FROM Orders";
                da = new SqlDataAdapter(sql, conn);
                conn.Open();
                ds = new DataSet();
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);          
                da.Fill(ds, "Orders");
                bsource.DataSource = ds.Tables["Orders"];
                dgv.DataSource = bsource;          
            }
        }

变量应该在函数内还是在函数外声明

在需要访问的范围内声明一个变量。如果在方法外部不需要它,就不要将它声明为字段,而是声明为局部变量。这样你就简化了代码,避免了严重的bug。

在这种情况下,我将使用局部变量。由于特定于变量类型的另一个原因。你应该在完成后立即关闭连接。否则,连接池(默认情况下已启用)将假定它仍在使用中。因此,它将打开另一个物理连接,而不是重用相同的物理连接,这将降低性能,有时会导致异常。

您可以使用using -语句确保即使出现错误连接也会被处理/关闭:

private void LoadData()
{
    DataSet ds = new DataSet();
    string sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," + "ShipName, ShipCountry FROM Orders";
    string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" + "Integrated Security=SSPI;";
    using(var conn = new SqlConnection(connectionString))
    using(var da = new SqlDataAdapter(sql, conn))
    {
        // if you use DataAdapter.Fill you don't need to open the connection 
        da.Fill(ds, "Orders");
        // ...    
    }
}

尽可能在嵌套范围内声明该变量,这样垃圾收集器就可以在不再需要它时立即删除它。

声明变量的两种方式的主要区别在于使用它们的方式。在LoadData函数中,您声明sql字符串并在SqlDataAdapter之后立即使用它,然后应该在函数中进行声明,因为您使用它来"及时"调用之后的方法。如果您希望能够读取、修改或获取某个变量的值,但在函数之外,那么您应该在编写类时立即声明它。TLDR:这完全取决于您是只在某个函数中使用该变量,还是希望它可以被许多可能想要操作该变量的方法访问。

您应该始终选择最严格但可能的方法,这不仅指变量,而且指几乎所有内容:字段,属性,方法,类可见性等。通过这样做,您可以最大限度地减少出错的机会(意外地使用此时不打算使用的变量、字段和方法)。如果你发现范围太窄了,你几乎总是可以很容易地扩大它,反之则会造成困难…