0

我有一个“游戏类”,看起来这样:

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当您仅将其保留在一种方法中时,这似乎很方便。但是,如果将其保留为成员变量,如何以最佳方式解决此问题?

4

1 回答 1

1

我希望你正在寻找这个:

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();
于 2013-09-11T19:23:16.880 回答