C#销毁或禁用类的特定对象

问题描述 投票:-3回答:1

我有一个Windows窗体和一个名为testclass.cs的类。以下示例代码适用于testclass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testApp
{
     public class testclass
    {
       public void disableEverything()
       {
           //some operations goes here
       }
       public void welcome()
       {
         //some code goes here
       }
    }
 } 

在我的表单中,我在按钮单击事件中有创建对象的代码,下面的代码显示了form1

       using System;
       using System.Collections.Generic;
       using System.Linq;
       using System.Text;

       namespace testApp
       {
          public partial class Form1: Form
          {
            private void button1_Click(object sender, EventArgs e)
            {
               testclass obj = new testclass();
               obj.welcome();

            }
          }
        }

我的问题是,如果我点击button1五次,它将创建类testclass的5个对象。假如我想调用某些类对象的disableEverything方法,如第3个对象,第二个对象,我怎么称呼这个?我应该使用List<testclass>并致电list[index].disableEverything()。建议我这个很好的灵魂

c# list class object destroy
1个回答
1
投票

我不知道你的实现是什么,但对于非托管资源,你可以实现IDisposable,并使用“Using”在工作后释放资源:

namespace testApp
{
  public class testclass : IDisposable
  {
      bool disposed = false;
     //Instantiate a SafeHandle instance.
      SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
   { 
     Dispose(true);
     GC.SuppressFinalize(this);           
   }

   // Protected implementation of Dispose pattern.
   protected virtual void Dispose(bool disposing)
   {
     if (disposed)
      return; 
     if (disposing) {
      handle.Dispose();
      // Free any other managed objects here.
      //
    }

    // Free any unmanaged objects here.
     //
    disposed = true;
   }  


    public void welcome()
    {
         //some code goes here
     }
   }
 }

private void button1_Click(object sender, EventArgs e)
{
       using (var obj = new testclass())
       {

       }
 }

https://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx

© www.soinside.com 2019 - 2024. All rights reserved.