Thursday, November 12, 2009

Reflection-Call the Method in a Type

Here we want to write code equivallent to:

DateTime d = new DateTime(2008, 5, 1);
Console.WriteLine(d.ToShortDateString());

What we do is:

Firstly, we must create an instance of the DateTime object, which
requires you to create an instance of ConstructorInfo and then call the ConstructorInfo to Invoke method.

Type t = typeof(DateTime);
//Create a Type object
ConstructorInfo ci = t.GetConstructor(new Type[] { typeof(int), typeof(int),
typeof(int) });
//Type.GetConstructor requires a Type array,
Object d = ci.Invoke(new Object[] { 2008, 5, 1 });
//ConstructorInfo.Invoke requires an Object array.

Next, to call DateTime.ToShortDateString, we
must create an instance of MethodInfo representing the method and then
call MethodInfo.Invoke.

MethodInfo dToShortDateString = t.GetMethod("ToShortDateString");
Console.WriteLine((string)dToShortDateString.Invoke(d, null));

No comments: