Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Generate and Execute Dynamic Script With .NET  : Page 2

Use the System.Reflection classes in the .NET Framework to write, execute, and interact with code you write dynamically at run-time from your applications.


advertisement
The System.Reflection.Assembly class is one of the most important classes for implementing reflection-based techniques in your applications, because it exposes several methods for loading assemblies, which let you load a new assembly at runtime. After loading an assembly, you can use an instance of the Assembly object to query the assembly manifest data, determine available types for reference, and view metadata included with that block of application code.

The Assembly.CreateInstance method supports dynamic invocation. You can use it to create a type reference based on the assembly. Because assemblies can contain numerous types, the Assembly class needs to support a method that returns a System.Type object for a specified class. It does that through the GetType method as shown the following code excerpt:

// C# code object oClass; Type tType; string strFileName; string strClass; Assembly asm = Assembly.LoadFrom(strFileName); oClass = asm.CreateInstance(strClass); tType = asm.GetType(strClass);

The preceding code fragment shows how to use an Assembly object to load an assembly using the overloaded LoadFrom method, create an instance of a type reference using the assembly, and then create a System.Type object that represents the type reference by using the GetType method. Finally, you can use the Type object to invoke class members dynamically, using the overloaded InvokeMember method.

// C# code object[] oArguments = new object[0]; object oReturn = tType.InvokeMember("YourMethod", BindingFlags.Default | BindingFlags.InvokeMethod, null, oClass, oArguments);

The preceding fragment demonstrates invoking the YourMethod member of the assembly using the Type instance obtained from the previous example. Note that the array oArguments must contain any input parameters required by the method; in this example oArguments is an array with 0 elements. By using the Assembly object and the Type object as shown in the examples you can load an assembly at runtime, create a reference to one of the assembly types, and then dynamically invoke one of the type methods.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap