在 C# 中实现 IDisposable

Implementing IDisposable in C#

我正在尝试在示例程序中实现 IDisposable。如果我在 using 块语句中使用 SqlConnection class,它会自动处理它。

public int testCon()
{
    using (SqlConnection conn = new SqlConnection("Conn string"))
    {
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText = "SELECT COUNT(1) FROM Carsd";

            return (int)cmd.ExecuteScalar();
        }
    }
}

我创建了一个 class 并实现了 IDisposable。我在 using 块语句中创建了一个新实例。

class Program 
{
    static void Main(string[] args)
    {
        testDispose objTestDispose;

        using (objTestDispose = new testDispose())
        {
            objTestDispose.UserName = "testUser";
            objTestDispose.PassWord = "testPassword";                                
        }

        Console.WriteLine("Check obj of testDispose Class" + objTestDispose.UserName);
        Console.WriteLine("Check obj of testDispose Class" + objTestDispose.PassWord);
        Console.ReadLine();

    }        
}

public class testDispose : IDisposable
{
    public string UserName { get; set; }
    public string PassWord { get; set; }

    public void Dispose()
    { }              
}

我相信,使用块会自动调用 dispose 方法。因此,如果我在 using 块中创建一个新实例,它将在现有 using 块之后被释放。但是,我仍然能够在使用 block.WHY 之外访问 objTestDispose 对象吗?

求推荐。

更新

Mr.BWA..谢谢你让我的问题重复。但你应该知道我是一个学生和学习者。我脑子里有这个问题,所以我在这里问了。 **您不能说 IDisposable 接口仅适用于非托管资源。**我也可以删除托管资源。这取决于实际情况。根据以下 link -

What if your object has allocated a 250MB System.Drawing.Bitmap (i.e. the .NET managed Bitmap class) as some sort of frame buffer? Sure, this is a managed .NET object, and the garbage collector will free it. But do you really want to leave 250MB of memory just sitting there – waiting for the garbage collector to eventually come along and free it? What if there's an open database connection? Surely we don't want that connection sitting open, waiting for the GC to finalize the object.

If the user has called Dispose() (meaning they no longer plan to use the object) why not get rid of those wasteful bitmaps and database connections?

So now we will:

get rid of unmanaged resources (because we have to), and get rid of managed resources (because we want to be helpful)

Dispose 被调用,但它不会破坏对象本身(您会注意到框架中的很多 IDiposable 类 另外还有a IsDisposed 属性表示非托管资源是否已经释放)

您仍然可以访问它,因为您将它定义在 using 块的范围之外,并且您没有将它设置为 null。

请注意,using 不会将对象设置为 null,它只是意味着将调用您的 Dispose() 方法,这为您提供了一种合同保证的方式来处理任何非托管资源否则不会被垃圾收集器清理。

你还应该考虑你的陈述的逻辑:

I believe, using block automatically call dispose method. So, if I am create a new instance in using block, it would be dispose after existing using block.

...一个对象如何将它自己的自身设置为空?

来自MSDN

ID一次性接口

Provides a mechanism for releasing unmanaged resources.

The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

这用于释放未管理的资源,而不是用于销毁对象本身。