03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Running Scripts ❘ 593<br />

The program then sets the value of the Echoer object’s Message field. It uses the Echoer type’s<br />

GetField method to get a FieldInfo object representing the field. It then uses the FieldInfo<br />

object’s SetValue method to set the field’s value for the Echoer instance.<br />

The last task the program must perform is invoking the Echoer object’s ShowMessage method. To<br />

do that, it calls the Echoer type’s GetMethod method to get a MethodInfo object representing the<br />

ShowMessage method. It creates an array of objects to hold the parameters that should be passed<br />

to the ShowMessage. Finally, it calls the MethodInfo object’s Invoke method, passing it the Echoer<br />

instance for which it should invoke the method and the argument array.<br />

This is an awful lot of work to simply display a message box, but the techniques used by the<br />

InvokeEchoer program show how to load and explore an assembly at run time. With a little more<br />

work and experimentation, you could modify the program to perform other tasks such as<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

Discover the classes defined by an assembly.<br />

Create instances of a class.<br />

Learn what fields, properties, and methods are defined by each class.<br />

Get and set field and property values.<br />

Invoke static methods and instance methods.<br />

Dangerous DLLs<br />

Load an assembly at run time only if you are sure it is safe. If a hacker inserts a<br />

bogus DLL in a directory where your code is looking for assemblies, you might be<br />

tricked into executing dangerous code.<br />

Running Scripts<br />

Reflection lets a program learn about existing code. The classes in the System.CodeDom.Compiler<br />

namespace enable a program to compile completely new code at run time. You can then use refection<br />

to execute the methods defined by the newly compiled code.<br />

Time Saver<br />

Compiling code at run time is fairly slow, so it’s not a good way to provide<br />

features that you know about at design time. If you know at design time that<br />

the program needs to do something, just compile that code right into the executable<br />

program. You only need to compile code at run time to run scripts and<br />

execute code that you can’t predict ahead of time.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!