Introduction
In previous article on Getting Type Information using Reflection in .NET we discovered information about an assembly and the types it contains. Our next step is to create an object and invoke its properties or methods from that information. The .NET Framework provides the means to create an object and to invoke its members dynamically.
The key to doing this is the Activator class, which is a member of the System.Reflection namespace.
Activator class
The Activator class contains only static methods, so you never have to declare an instance of the class. Using the Activator class involves late binding. late binding
In which the exact type of the object is not known until runtime.
Early Binding
which you use when you create an object using the new keyword. Early binding is always preferable to late binding, because early binding ensures that errors will be determined when you compile the program. Early binding usually results in faster program load times as well. Late binding, however, allows you to create an object without knowing its type.
The following program, Invoke.cs, extends the Asy.cs program and creates objects of the ASM structure and the clsASM class in the ASMNAME assembly:
Invoke.cs -- Demonstrates dynamically invoking an object
using System; using System.Reflection;
namespace nsReflection { class clsMain { static public void Main () {
// Load the ASMNAME assembly.
Assembly asy = null;
try { asy = Assembly.Load ("ASMNAME"); }
catch (Exception e) { Console.WriteLine (e.Message); return; }
// Parameter array for a ASM object.
object [] parmsSUC = new object [2] {1, 1};
// Parameter array for a clsASM object.
object [] parmsASM = new object [3] {‘v’, ‘z’, ‘g’};
// Get the type of clsASM and create an instance of it.
Type asm1 = asy.GetType("nsASM.ASMNAME");
object obj = Activator.CreateInstance (asm1, parmsASM);
// Get the property info for the area and show the area.
PropertyInfo p = asm1.GetProperty ("Name");
Console.WriteLine ("The Name of the city is " +p.GetValue(obj, null));
// Get the POINT type and create an instance of it. Type asm2 = asy.GetType("nsASM.ASM");
object pt = Activator.CreateInstance (asm2, parmsSUC);
// Show the asm2 using object's ToString() method. Console.WriteLine ("The ASM is " + pt.ToString ()); } } }
Compiling and running Invoke.cs results in the following output:
The name of the city is vizag. The ASM is success
Assuming that you do not have the source code for the ASMNAME assembly, you now have discovered information about the assembly and its types, and you’ve created objects indirectly using theActivator class.
Summary
This article explains how to invoke object dynamically using system.Reflections see also http://www.dotnetspider.com/kb/Article2055.aspx
|
No responses found. Be the first to respond and make money from revenue sharing program.
|