实现了IDisposable正确实现了、正确、IDisposable

2023-09-02 01:35:45 作者:千疮百孔总好过一刀致命

在我的班级我实现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,C分析我的$ C $说,要正确实现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(布尔)在用户或标记类型密封。一个调用Dispose(假)应该只清理本地资源。一个调用Dispose(真)应该清理托管和本机资源。 stman User.cs 10

CA1063 Implement IDisposable correctly Provide an overridable implementation of Dispose(bool) on 'User' or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources. stman User.cs 10

有关参考:CA1063:实现IDisposable正确

我已经通过这个页面阅读,但我怕我真的不明白什么需要在这里完成。

I've read through this page, but I'm afraid I don't really understand what needs to be done here.

如果任何人都可以在更多的lamens来解释的问题是什么和/或IDisposable的如何实施,这将真正帮助!

If anyone can explain in more lamens terms what the problem is and/or how IDisposable should be implemented, that will really help!

推荐答案

这将是正确的实施,虽然我没有看到任何你需要在$ C $处置c您发布。你只需要实现的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:

您有非托管资源 您正拿着的东西本身是一次性的参考。

在C您发布的需求$ C $没有予以处置。

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.

}