什么时候应该使用Using语句?

Hel*_*der 7 c# using-statement

很多人在SO上指出我应该using更频繁地使用陈述.所以我在练习.

问题是我无法决定何时使用它以及何时不使用它.当我认为我应该使用它时,我会收到错误,例如在这个例子中(PS.HashPhrase是我创建的类):

        using (HashPhrase hash = new HashPhrase())
        {
            connection.ConnectionString =
                "Provider=Microsoft.ACE.OLEDB.12.0;" +
                "Data Source=" + filePath + ";" +
                "Persist Security Info=False;" +
                "Jet OLEDB:Database Password=" + hash.ShortHash(pass) + ";";
        }
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误: 'Password_Manager.HashPhrase': type used in a using statement must be implicitly convertible to 'System.IDisposable'

但在这个例子中它工作正常:

    using (OleDbConnection connection = new OleDbConnection())
    {
        connection.ConnectionString =
            "Provider=Microsoft.ACE.OLEDB.12.0;" +
            "Data Source=" + filePath + ";" +
            "Persist Security Info=False;" +
            "Jet OLEDB:Database Password=" + hash.ShortHash(pass) + ";";

        using (OleDbCommand command = new OleDbCommand(sql, connection))
        {
            try
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

有没有快速指导如何确定何时using应该使用声明?

Luk*_*keH 15

你的问题已经触及了答案.

如果类型实现了IDisposable接口,那么你应该using尽可能地使用(也就是说,总是,除非有令人信服的理由不这样做).

如果类型没有实现IDisposable那么你就不能使用using,编译器会告诉你,正如你已经发现的那样.


Chr*_*tow 5

using每当类实现IDisposable接口时,都应该使用语句.

它是将对象包装在try-finally块中的简写,以确保Dispose始终调用对象的方法来释放任何资源,无论是否抛出异常.

要进行检查,请在Visual Studio中右键单击类名,然后选择" 转至声明"以在对象浏览器中将其打开.然后,您可以轻松检查类或其基类型是否实现IDisposable.