Monday, June 20, 2005
Reflection - Getting Method Info
Reflection - obtaining information about a type, comes from the way the reflection process works: A Type object questions and it returns (reflects) the information associated with the type, back to you.
It allows one to learn and use the capabilities of types that are known only at runtime.
Obtaining Information about Members
Once a Type object is obtained, the list of all its methods can be retrived by using the
It returns an array of MethodInfo objects that describe the methods supported by the invoking type.
Here is a program that uses reflection to obtain the methods supported by a class called MyClass.
(Notes obtained from C#: The Complete Reference by Schildt)
It allows one to learn and use the capabilities of types that are known only at runtime.
Obtaining Information about Members
Once a Type object is obtained, the list of all its methods can be retrived by using the
GetMethods() method. It has this form:MethodInfo[] GetMethods()It returns an array of MethodInfo objects that describe the methods supported by the invoking type.
Here is a program that uses reflection to obtain the methods supported by a class called MyClass.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace AnalyzeMethods
{
class MyClass
{
int x;
int y;
public MyClass(int i, int j)
{
x = i; y = j;
}
public int sum()
{
return x + y;
}
public bool isBetween(int i)
{
return (x < i && i < y ) ? true : false;
}
public void set(int a, int b)
{
x = a;
y = b;
}
public void set(double a, double b)
{
x = (int)a;
y = (int)b;
}
public void show()
{
Console.WriteLine("x: {0}, y: {1}", x, y);
}
}
class RelectionDemo
{
static void Main(string[] args)
{
Type t = typeof(MyClass);
Console.WriteLine("Analyzing methods in " + t.Name);
Console.WriteLine();
Console.WriteLine("Methods supported: ");
// 1st way to call
//MethodInfo[] mi = t.GetMethods();
// 2nd way to call
// Only method declared by MyClass are obtained.
MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public
| BindingFlags.Instance );
// Dispaly method information
foreach (MethodInfo m in mi)
{
// Display return type and name
Console.Write("\t" + m.ReturnType.Name +
" " + m.Name + "(");
// Display parameters
ParameterInfo[] pi = m.GetParameters();
for (int i = 0; i < pi.Length; i++)
{
Console.Write(pi[i].ParameterType.Name +
" " + pi[i].Name);
if (i + 1 < pi.Length)
Console.Write(", ");
}
Console.WriteLine(")");
}
}
}
}
(Notes obtained from C#: The Complete Reference by Schildt)