I am writing a .NET web application in which administrators can customize various forms of data entry presented to their users. There are about a dozen different types of fields that administrators can create and customize (for example, text, numeric, drop-downs, file downloads). All fields have a common set of basic attributes / behavior (is a field required? Will it have a default value?). There are also a number of field-specific attributes / behavior (there is a data source attribute in the drop-down list but no text field). For simplicity, I leave many other characteristics of the problem area.
The class hierarchy is simple: an abstract superclass that encapsulates common behaviors / attributes and about half a dozen specific subclasses that deal with field specifics.
Each type of field is visualized (i.e. mapped) as a specific type of control for the .NET server, all of which come from System.Web.UI.Control.
I created the following code to map the values ββbetween the objects in the field region and their corresponding user interface control:
public static void Bind(Control control, IList<DocumentFieldBase> fieldBaseList)
foreach (DocumentFieldBase fieldBase in fields){
if (typeof (DocumentFieldText).IsInstanceOfType(fieldBase)){
TextBox textbox = (TextBox) control;
textbox.Text = (fieldBase as DocumentFieldText).GetValue();
}
if (typeof (DocumentFieldDropDown).IsInstanceOfType(fieldBase)){
DropDown dropDown= (DropDown) control;
dropDown.Text = (fieldBase as DocumentFieldSelectOne).GetValue().Text;
dropDown.DataSource= (fieldBase as DocumentFieldSelectOne).DataSource;
dropDown.Id= (fieldBase as DocumentFieldSelectOne).GetValue().Id;
}
}
}
I want to discard these unholy if statements that do type checking. The approach I shot was to create a method overload for each field / control combination using a subclass. For example:
public static void Bind(TextBox control, DocumentFieldText fieldText){
}
public static void Bind(DropDown control, DocumentFieldDropDown fieldDropDown){
}
, .NET, runtime : :
foreach (DocumentFieldBase field in fields){
Control control = FindControl(field.Identifier);
Bind(control, field)
}
, , : "1": "System.Web.UI.Control" "TextBox".
TextBox, .
a), b) ?