问题描述
在我的课程中,我实现了 IDisposable
如下:
In my classes I implement IDisposable
as follows:
public class User : IDisposable
{
public int id { get; protected set; }
public string name { get; protected set; }
public string pass { get; protected set; }
public User(int UserID)
{
id = UserID;
}
public User(string Username, string Password)
{
name = Username;
pass = Password;
}
// Other functions go here...
public void Dispose()
{
// Clear all property values that maybe have been set
// when the class was instantiated
id = 0;
name = String.Empty;
pass = String.Empty;
}
}
在 VS2012 中,我的代码分析说要正确实现 IDisposable,但我不确定我在这里做错了什么.
具体内容如下:
In VS2012, my Code Analysis says to implement IDisposable correctly, but I'm not sure what I've done wrong here.
The exact text is as follows:
CA1063 正确实现 IDisposable 在用户"上提供可覆盖的 Dispose(bool) 实现或将类型标记为密封.调用 Dispose(false) 应该只清理本机资源.调用 Dispose(true) 应该清理托管资源和本机资源.stman User.cs 10
我已经通读了这个页面,但恐怕我不太明白这里需要做什么.
I've read through this page, but I'm afraid I don't really understand what needs to be done here.
如果有人能更通俗地解释问题是什么和/或应该如何实现 IDisposable
,那真的很有帮助!
If anyone can explain in more layman's terms what the problem is and/or how IDisposable
should be implemented, that will really help!
推荐答案
这将是正确的实现,尽管我在您发布的代码中没有看到您需要处理的任何内容.您只需要在以下情况下实现 IDisposable
:
This would be the correct implementation, although I don't see anything you need to dispose in the code you posted. You only need to implement IDisposable
when:
- 您有非托管资源
- 你坚持引用本身是一次性的东西.
您发布的代码中没有任何内容需要处理.
Nothing in the code you posted needs to be disposed.
public class User : IDisposable
{
public int id { get; protected set; }
public string name { get; protected set; }
public string pass { get; protected set; }
public User(int userID)
{
id = userID;
}
public User(string Username, string Password)
{
name = Username;
pass = Password;
}
// Other functions go here...
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
}
// free native resources if there are any.
}
}
这篇关于正确实现 IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!