using System; using System.ComponentModel; // Define a custom component that implements IDisposable. public class MyComponent : Component, IDisposable { // Define a private field to track the disposal state. private bool disposedValue = false; // Implement the IDisposable.Dispose method. protected virtual void Dispose(bool disposing) { if (!disposedValue) { // Dispose of any managed resources here, if necessary. if (disposing) { // Dispose of managed resources. } // Dispose of any unmanaged resources here, if necessary. // Mark the object as disposed. disposedValue = true; } } // Override the finalizer to call the IDisposable.Dispose method. ~MyComponent() { Dispose(false); } // Implement the IDisposable.Dispose method. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } // Define a class that implements IContainer. public class MyContainer : IContainer { // Define a private list of contained components. private Listcomponents = new List (); // Implement the IContainer.Add method. public void Add(IComponent component) { if (component is Component) { components.Add(component as Component); } else { throw new ArgumentException("Component must inherit from System.ComponentModel.Component."); } } // Implement the IContainer.Remove method. public void Remove(IComponent component) { if (component is Component) { components.Remove(component as Component); } } // Implement the IContainer.Components property. public ComponentCollection Components { get { return new ComponentCollection(components.ToArray()); } } // Implement the IDisposable.Dispose method. public void Dispose() { foreach (Component component in components) { component.Dispose(); } } } // Example usage. MyComponent component = new MyComponent(); MyContainer container = new MyContainer(); container.Add(component); container.Dispose();
using System; using System.ComponentModel; public class ExampleComponent : Component { // Define a private field to track the disposal state. private bool disposedValue = false; // Implement the IDisposable.Dispose method. protected override void Dispose(bool disposing) { if (!disposedValue) { // Dispose of any managed resources here, if necessary. if (disposing) { // Dispose of managed resources. } // Dispose of any unmanaged resources here, if necessary. // Call the base class implementation. base.Dispose(disposing); // Mark the object as disposed. disposedValue = true; } } } // Example usage. ExampleComponent component = new ExampleComponent(); component.Dispose();This example defines a custom component class and overrides the Dispose method to provide custom disposal logic. The example creates an instance of the custom component and explicitly calls the Dispose method, which cleans up any resources allocated by the component. Package library: System.ComponentModel