So far, we have worked with the .NET type or object. But with reflection, we can actually do it immediately on runtime, knowing the name of the class that we want to instantinate, there are many ways to do this, but I like to get the constructor's reference which I use I want to open it, and then want to use the return value as my value. This is just an example of doing this code first, then I will explain it all:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
Type testType = typeof(TestClass);
ConstructorInfo ctor = testType.GetConstructor(System.Type.EmptyTypes);
if(ctor != null)
{
object instance = ctor.Invoke(null);
MethodInfo methodInfo = testType.GetMethod("TestMethod");
Console.WriteLine(methodInfo.Invoke(instance, new object[] { 10 }));
}
Console.ReadKey();
}
}
public class TestClass
{
private int testValue = 42;
public int TestMethod(int numberToAdd)
{
return this.testValue + numberToAdd;
}
}
}
I have defined a simple class for a test called test class. It is only a private sector and a public law, the method gives the value of private property, along with the value of the parameter is added. Now, what we want, is to create a new example of this test class, call Testimth and output the results in the console.
In this example, we have the luxury of being able to use the type () directly on the test class, but at some point, you may have to do it completely by using the name of the desired class. In that case, Can get a reference on it, where it has been declared, as shown in the section about the type.
Therefore, with a type reference for the class, we ask for the default constructor using the GetConstructor () method, as a parameter, to pass the System.Type.EmptyTypes. If we wanted a specific constructor, then we would have to provide an array of types, each defining controller that we were looking for.
Once we have a reference to the constructor, we only call the Invek () method to create a new instance of the test class class. We pass the null as aggressive, because we are not specifying any parameters. We use GetMethod () with the name of the method, which receive the TestMethod () function, and then we use the magic of the invoke () method to call this function. At this time we need to specify a parameter as an array of objects. We do it on-fly, only 10 parameters specify us the only parameter, and then we output the result of the call of the method. All this through the magic of reflection!