Implementing IDisposable in C#
我正试图在示例程序中实现IDisposable。如果我在using块语句中使用sqlconnection类,它将自动释放它。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); } } } |
我已经创建了一个类并实现了IDisposable。我在using块语句中创建了一个新实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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块之后被释放。但是,我仍然能够访问使用块之外的objTestDispose对象。为什么?
请建议。
乌达特
BWA先生……谢谢你把我的问题复制了。但你应该知道我是一个学生和学习者。我心里有这个问题,所以我在这里问过。**不能说IDisposable接口仅用于非托管资源。**我还可以删除托管资源。这取决于情况。根据以下链接-
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)
您仍然可以访问它,因为您在
注意,
你还应该考虑你的陈述的逻辑:
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
IDisposable接口
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.
这用于释放命名资源,而不是用于销毁对象本身。