CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
Figure 15-2. Late-bound method invocation
Invoking Methods with Parameters
When you wish to use late binding to invoke a method requiring parameters, you should package up the
arguments as a loosely typed array of objects. Recall that version 2.0.0.0 of CarLibrary.dll defined the
following method in the Car class:
public void TurnOnRadio(bool musicOn, MusicMedia mm)
{
if (musicOn)
MessageBox.Show(string.Format("Jamming {0}", mm));
else
MessageBox.Show("Quiet time...");
}
This method takes two parameters: a Boolean representing if the automobile’s music system should
be turned on or off, and an enum that represents the type of music player. Recall this enum was
structured as so:
public enum MusicMedia
{
musicCd,
// 0
musicTape,
// 1
musicRadio,
// 2
musicMp3
// 3
}
Here is a new method of the Program class, which invokes TurnOnRadio(). Notice that you are using
the underlying numerical values of the MusicMedia enumeration, to specify a “radio” media player.
static void InvokeMethodWithArgsUsingLateBinding(Assembly asm)
{
try
{
// First, get a metadata description of the sports car.
Type sport = asm.GetType("CarLibrary.SportsCar");
// Now, create the sports car.
object obj = Activator.CreateInstance(sport);
577