Method overload and polymorphism

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;
            }

            //more if statements left out for brevity
      }
}

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){
 //some implementation code
}
public static void Bind(DropDown control, DocumentFieldDropDown fieldDropDown){
 //some implementation code
}  

, .NET, runtime : :

foreach (DocumentFieldBase field in fields){
  Control control = FindControl(field.Identifier);
  Bind(control, field)
}

, , :   "1": "System.Web.UI.Control" "TextBox".

TextBox, .

a), b) ?

+5
3

"" : , , " ". # ( ) " ", , , (runtime) , , (runtime) .

, . , DocumentFieldBase ( ), Control ( ), .

, Control, , *... . , .

* - .

+5

# 4 . , .

# 4 :

foreach (DocumentFieldBase field in fields){
  dynamic control = FindControl(field.Identifier);
  Bind(control, field)
}

, ( VS2010b1).

Type Action<object>, ... (, , , ). : (

+6

, Bind() DocumentFieldBase, downcasting ? DocumentFieldBase , Control , ?

0

All Articles