To give you an example of the practical use of Reflection:
Suppose you are developing an application that you want to extend with plugins. These plugins are simple assemblies containing only a class named Person:
namespace MyObjects { public class Person { public Person() { ... Logic setting pre and postname ... } private string _prename; private string _postname; public string GetName() { ... concat variabes and return ... } } }
Well, plugins should extend your application at runtime. This means that the content and logic must be loaded from another assembly when your application is already running. This means that these resources are not compiled into your assembly, i.e. MyApplication.exe. Suppose they are in the library: MyObjects.Person.dll.
Now you are faced with the fact that you will need to extract this information and, for example, access the GetName () function from MyObjects.Person.
// Create an assembly object to load our classes Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + @"MyObjects.Person.dll"); Type objType = testAssembly.GetType("MyObjects.Person"); // Create an instace of MyObjects.Person var instance = Activator.CreateInstance(objType); // Call the method string fullname = (string)calcType.InvokeMember("GetName", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, instance, null);
As you can see, you can use System.Reflection to dynamically load resources in Runtime. This may help to understand how you can use it.
Take a look at the page to see examples of more detailed access to assemblies. This is basically the same content that I wrote.
Dennis Alexander
source share