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

发布于 2024-12-19 06:21:32 字数 1371 浏览 4 评论 0 原文

很多人指出我应该更频繁地使用 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) + ";";
        }

但它给了我一个错误: 'Password_Manager.HashPhrase': type used in a using语句必须隐式转换为“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);
            }
        }
    }

是否有任何快速指南如何确定何时应使用 using 语句?

A lot of people on SO pointed out that I should use using statement more often. So I am practicing.

The problem is that I can't decide when to use it and when not to use it. When I think I should use it, then I get errors such as in this example (PS. HashPhrase is a class created by me):

        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) + ";";
        }

But it gives me an error: 'Password_Manager.HashPhrase': type used in a using statement must be implicitly convertible to 'System.IDisposable'

But in this example it works fine:

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

Are there any quick guidelines how to determine when using statement should be used?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

倾城°AllureLove 2024-12-26 06:21:32

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

如果类型实现 IDisposable接口,那么您应该旨在使用 using每当可能(也就是说,总是如此,除非有令人信服的理由不这样做)。

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

Your question already touches on the answer.

If the type implements the IDisposable interface then you should aim to use using whenever possible (that is, always, unless there's a compelling reason not to).

And if the type doesn't implement IDisposable then you can't use using, and the compiler will tell you so, as you've already discovered.

失退 2024-12-26 06:21:32

每当类实现 using 语句>IDisposable 接口。

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

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

You should use a using statement whenever the class implements the IDisposable interface.

It's a shorthand for wrapping the object in a try-finally block to ensure the object's Dispose method is always called to release any resources, regardless of whether an exception is thrown.

To check, right-click the class name in Visual Studio and select Go To Declaration to open it in the Object Browser. You can then check easily whether the class or its base types implement IDisposable.

幻想少年梦 2024-12-26 06:21:32

在类中,

using (var r = new R())
{
   // use r
}

R 应该实现 IDispose 接口。

In

using (var r = new R())
{
   // use r
}

the class R should implement the IDisposing interface.

岁月染过的梦 2024-12-26 06:21:32

最简单的方法是查看对象是否实现了 IDisposable 接口。因此,右键单击相关对象/类,从下拉列表中选择转到定义(或按 F12),然后查看该类是否实现 IDisposable。请注意,在实现许多接口/其他类的类中,您可能需要实际检查这些类以查看它们是否也实现 IDisposable。

The easiest way is to see if the object implements the IDisposable interface. So, right click the object/class in question, select Go to Definition from the dropdown (or press F12), and see if the class implements IDisposable. Note, in a class that implements many interfaces/other classes, you may need to actually check those classes to see if they implement IDisposable as well.

失与倦" 2024-12-26 06:21:32

大多数时候,我不会首先检查类是否实现了 IDisposable(因为这可能隐藏在基类中),如果我认为,我只需编写一个Using 块这是有道理的,如果编译失败,我会回滚到标准结构。懒惰的?是的,有一点。但它可以更快。

例如,VB:

Using oSerializer As XmlSerializer = New XmlSerializer(GetType(MyType))
    ...
End Using

例如,C#:

using (XmlSerializer serializer = new XmlSerializer(typeof(MyType)))
{
    ...
}

虽然我认为这应该是可能的,但上述片段实际上都不会编译,因为 XmlSerializer 没有实现 IDisposable (老实说,考虑到 XmlReaderXmlWriter 等相关类确实实现了这一点,我觉得有点奇怪IDisposable)。

那么你就可以回滚到标准结构。

VB:

Dim oSerializer As XmlSerializer = New XmlSerializer(GetType(MyType))
...

C#:

XmlSerializer serializer = new XmlSerializer(typeof(MyType));
...

我当然同意在可用的情况下使用 Using;它干净、简洁,您可以得到广告中所宣传的处置和清理的效果。好的!

Most of the time I don't check first if a class implements IDisposable (since this might be buried in a base class), I just code a Using block if I think it makes sense, and if it fails to compile, I roll back to a standard construction. Lazy? Yeah, a bit. But it can be faster.

Eg, VB:

Using oSerializer As XmlSerializer = New XmlSerializer(GetType(MyType))
    ...
End Using

Eg, C#:

using (XmlSerializer serializer = new XmlSerializer(typeof(MyType)))
{
    ...
}

Though I think this should be possible, neither of the above fragments will actually compile because XmlSerializer doesn't implement IDisposable (which I find a bit strange to be honest considering that associated classes such as XmlReader and XmlWriter do implement IDisposable).

So then you can just roll back to standard construction.

VB:

Dim oSerializer As XmlSerializer = New XmlSerializer(GetType(MyType))
...

C#:

XmlSerializer serializer = new XmlSerializer(typeof(MyType));
...

I certainly agree with using Using where it's available; it's clean, concise and you get what's advertised in disposal and clean-up. Nice!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文