Tuesday, November 10, 2009

Example of using Reflection to get Constructor and Methods

We can use Assembly.Load, Assembly.LoadFile, Assembly.LoadFrom to load the assembly, and Assembly.GetType to create a Type object.

Here we just add a class, example see http://www.codersource.net/csharp_tutorial_reflection.html.

We use this example code:

public class TestDataType
{

public TestDataType()
{
counter = 1;
}

public TestDataType(int c)
{
counter = c;
}

private int counter;

public int Inc()
{
return counter++;
}
public int Dec()
{
return counter--;
}

}


In the Main class, add System.Reflection namespace. And we can use Type object's GetConstructs, GetMethods methods to get the information out.

The code is like:

TestDataType testObject = new TestDataType(15);
Type objectType = testObject.GetType();

ConstructorInfo[] info = objectType.GetConstructors();
MethodInfo[] methods = objectType.GetMethods();
foreach (ConstructInfo ci in info){....}
foreach (MethodInfo mi in methods){....}

...

Notice that, for the constructor, we get:
Void .ctor()
Void .ctor(Int32)
This is what we constructed.

For the methods, beside the one we constructed,
Int32 Inc()
Int32 Dec()
There are some implict Method, such as
System.ToString()
Equal()
GetHashCode()
We can see from ILDasm as well.

No comments: