猿问

正确实现IDisposable

在我的类中,我实现IDisposable如下:


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,但我不确定我在这里做错了什么。

具体文字如下:


CA1063正确实现IDisposable在“用户”上提供Dispose(bool)的可覆盖实现,或将类型标记为已密封。对Dispose(false)的调用应该只清理本机资源。对Dispose(true)的调用应该清理托管和本机资源。stman User.cs 10


供参考:CA1063:正确实施IDisposable


我已经阅读了这个页面,但是我担心我真的不明白这里需要做些什么。


如果任何人都可以用更多的术语来解释问题是什么和/或IDisposable应该如何实现,这将真的有帮助!


qq_花开花谢_0
浏览 802回答 3
3回答

吃鸡游戏

这将是正确的实现,虽然我没有看到您需要在您发布的代码中处置任何内容。您只需要在以下时间实施IDisposable:您有非托管资源你正在坚持引用本身就是一次性的东西。您发布的代码中没有任何内容需要处理。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.    }}
随时随地看视频慕课网APP
我要回答