正确处理成员变量中的一次性资源

本文关键字:一次性 资源 成员 变量 正确处理 | 更新日期: 2023-09-27 18:30:55

我有一个"游戏类",看起来像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
namespace MyGame
{
    class Game : GameWindow
    {
        Player player;
        List<Enemy> enemies;
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            // Initialize stuff here
        }
        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            base.OnUpdateFrame(e);
            // Call Update on the player and the enemies
        }
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);
            // Call Draw on the player and the enemies
        }
        static void Main(string[] args)
        {
            using (var game = new Game())
            {
                game.Run();
            }
        }
    }
}

但现在我遇到了一个障碍。Player对象和Enemy对象现在需要保存对需要手动分配和释放的 OpenGL 缓冲区的引用。C#中这种事情的建议解决方案似乎是使用IDisposable。 当您只是将其保存在一种方法中时,using似乎很方便。但是,如果您将其保留为成员变量,如何以最佳方式解决此问题?

正确处理成员变量中的一次性资源

我希望你正在寻找这个:

class Game : GameWindow, IDisposable
{
        private bool _disposed;
  public void Dispose()
        {
            // If this function is being called the user wants to release the
            // resources. lets call the Dispose which will do this for us.
            Dispose(true);
            // Now since we have done the cleanup already there is nothing left
            // for the Finalizer to do. So lets tell the GC not to call it later.
            GC.SuppressFinalize(this);
        }
 /// <summary>
        ///     Dispose client here
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (your_any_managed_unmanaged_resource != null)
                    {
                       //do cleanup
                    }
                }
                _disposed = true;
            }
        }
}

调用您的游戏

Game g = new Game();
g.Play();
g.Dispose();