I want to implement a class which stores different appearances for different controls. At first I thought to use generics, as such:
public class Appearance<T where T : Control> { ... }
but there are two problems. First of all, I want to use these appearances in a list for different controls, namely different T (impossible in this case). Secondly each control type's appearance will have different properties according to the control it is refering. So the solution is a base class (preferably abstract) and derived classes for each control type:
abstract class Appearance { ... }
public class TextBoxAppearance : Appearance { ... }
public class ComboBoxAppearance : Appearance { ... }
My problem now is that I would like to achieve encapsulation regarding the control types, each class concerns, namely:
public abstract class Appearance {
public abstract void updateAppearanceOf(Control control);
}
public class TextBoxAppearance : Appearance {
public void updateAppearanceOf([here I want to give TextBox instead of Control])
{
// implement update of TextBox
}
}
public class ComboBoxAppearance : Appearance {
public void updateAppearanceOf([here I want to give ComboBox instead of Control])
{
// implement update of ComboBox
}
}
Is this possible?
You can make your base class explicitly implement IAppearance
public interface IAppearance
{
void updateAppearanceOf(Control control);
}
public abstract class Appearance<T> : IAppearance where T : Control
{
void IAppearance.updateAppearanceOf(Control control)
{
if (control is T) updateAppearanceOf((T)control);
}
public abstract void updateAppearanceOf(T control);
}
public class TextBoxAppearance : Appearance<TextBox> {
public override void updateAppearanceOf(TextBox control)
{
// implement update of TextBox
}
}
This way all the classes implementing the abstract Appearance
just have to worry about how to handle their control.