When are C# “using” statements most useful?

后端 未结 14 1910
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 05:33

So a using statement automatically calls the dispose method on the object that is being \"used\", when the using block is exited, right?

But when is this necessary/benef

14条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 06:06

    I like to use them like this:

        static public void AddSampleData(String name)
        {
            String CreateScript = GetScript(String.Format("SampleData_{0}", name));
            using (IDbConnection MyConnection = GetConnection())
            {
                MyConnection.Open();
                IDbCommand MyCommand = MyConnection.CreateCommand();
                foreach (String SqlScriptLine in CreateScript.Split(';'))
                {
                    String CleanedString = SqlScriptLine.Replace(";", "").Trim();
                    if (CleanedString.Length == 0)
                        continue;
    
                    MyCommand.CommandText = CleanedString;
                    int Result = MyCommand.ExecuteNonQuery();
                }
            }
        }
    

    They work great for cases where you don't want to put error checking code only cleans up and passes the error on down. The alternative method would look like this:

        static public void AddSampleData(String name)
        {
            String CreateScript = GetScript(String.Format("SampleData_{0}", name));
    
            IDbConnection MyConnection = null;
            try
            {
                IDbConnection MyConnection = GetConnection();
                MyConnection.Open();
                IDbCommand MyCommand = MyConnection.CreateCommand();
                foreach (String SqlScriptLine in CreateScript.Split(';'))
                {
                    String CleanedString = SqlScriptLine.Replace(";", "").Trim();
                    if (CleanedString.Length == 0)
                        continue;
    
                    MyCommand.CommandText = CleanedString;
                    int Result = MyCommand.ExecuteNonQuery();
                }
            }
            finally
            {
                if (MyConnection != null
                    && MyConnection.State == ConnectionState.Open)
                    MyConnection.Close();
            }
        }
    

    And frankly, which method is easier to read? Same thing with forms:

        public void ChangeConfig()
        {
            using (ConfigForm MyForm = new ConfigForm())
            {
                DialogResult ConfigResult = MyForm.ShowDialog();
                if (ConfigResult == DialogResult.OK)
                    SaveConfig();
            }
    
            ConfigForm MyForm = new ConfigForm();
            DialogResult ConfigResult = MyForm.ShowDialog();
            MyForm.Dispose();
            if (ConfigResult == DialogResult.OK)
                SaveConfig();
        }
    

提交回复
热议问题