المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Removing duplicate object instances?



C# Programming
10-03-2011, 10:13 PM
Hey. Sorry if i have not quite got the lingo but here goes.

So i have declared an instance ('finalCellCompiler') of the CompileFinalCell class globally (for access across the whole form) and upon clicking the twoDDisplay button on the form finalCellCompiler is initialised with the *new keyword.

The CompileFinalCell class features the IDisposable wrapper and a dispose method to dispose of the object. A seperate reset button calls the clear method to get rid of the finalCellCompiler object.

The issue i have is that after calling the reset method and subsequently the twoDDisplay i get two instances of the finalCellCompiler as when i click a third button 'depositNext' (which is handled inside the CompileFinalCell class) the messageBox is call twice from each instance.

I am trying to figure out a way of replacing the original instance without creating major modifications to my code.

Any help would be greatly appreciated. Thanks.

public partial class Form1 : Form { //FIELD VARIABLES private CompileFinalCell finalCellCompiler; private void twoDDisplay_Click(object sender, EventArgs e) { finalCellCompiler = new CompileFinalCell(this, fibrePositionGenerator, unitCellData.outerCellSize, finalBeamForce, finalShellForce); } private void Clear() { if (finalCellCompiler != null) { finalCellCompiler.Dispose(); finalCellCompiler = null; } GC.Collect(); } } class CompileFinalCell : IDisposable { //FIELDS Form1 _form1Data; // Reference copy of the form1Data //CONTRUCTOR public CompileFinalCell(Form1 originalFormData, FibrePositionGenerator fibreData, SizeF outerCell, ForceDirectedAlgorithm beamForce, ForceDirectedAlgorithm shellForce) { //Assign field variables by reference _form1Data = originalFormData; //Create event handlers _form1Data.depositNext.Click += new EventHandler(depositNext_Click); } private void depositNext_Click(object sender, EventArgs e) { MessageBox.Show("Button clicked"); } public void Dispose() { GC.SuppressFinalize(this); } }