C#make class static?

fed*_*dab 3 c# static interface

我有一个这样的课:

class ContentManager : IDisposable
{
    List<int> idlist = new List<int>();

    public int Load(string path)
    {
        //Load file, give content, gets an id

        //...

        int id = LoadFile(myfilecontent);

        idlist.Add(id);
        return id;
    }

    public void Dispose()
    {
        //Delete the given content by id, stored in idlist

        foreach(int id in idlist)
        {
            DeleteContent(id);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想让它成为静态的,因为我只需要一个实例,并且可以在不提供实例的情况下从其他所有类访问该函数.

我可以使其中的每个变量都是静态的,函数是静态的.

但我的问题是这个IDisposable.我不能在静态类中使用接口.我怎么能在最后做一些动作?我的意思是我可以删除该接口,但将函数保留在其中并使用我的主类,当我的主类被释放时,我调用ContentManager.Dispose().但是当我忘记在我的主...

你有一个很好的解决方案吗?确保每次程序关闭时都调用Dispose?

编辑:我在图形卡中加载数据并返回指针.当我的应用程序关闭时,我需要从显卡中删除内容.为了安全起见,一切都被删除了,我使用了dispose.

Ada*_*lin 7

我会把你的类留作非静态类并实现单例模式.我添加了一个如何将其用作单例的示例:

public class ContentManager : IDisposable
{
    private List<int> idlist = new List<int>();
    private static ContentManager instance;

    private ContentManager () {}

    public static ContentManager Instance
    {
       get 
       {
           if (instance == null)
           {
               instance = new ContentManager ();
           }
           return instance;
       }
    }

    public int Load(string path)
    {
        int id = LoadFile(myfilecontent);    
        idlist.Add(id);
        return id;
    }

    public void Dispose()
    {
        foreach(int id in idlist)
        {
            DeleteContent(id);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)