The blog has moved to a new address. The blog is now located at http://devintelligence.com

Adsense

Thursday, January 31, 2008

System.Reflection - MethodInfo class (usage)

A MethodInfo class provides detailed information about a single method of a class or an interface. The reflected method may be a static method or an instance method. The MethodInfoSpy example shows how to obtain the method information of a class including the access modifiers, type or input parameters:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Reflection;

namespace MethodInfoSpy
{
class Program
{

static void Main(string[] args)
{
Type type = typeof(Program);
MethodInfo [] methodInfos = type.GetMethods();
foreach (MethodInfo methodInfo in methodInfos)
{
// retrive method information
Console.WriteLine("Name: {0}, Public: {1}, Is Static: {2}, Return Type: {3}",
methodInfo.Name,
methodInfo.IsPublic,
methodInfo.IsStatic,
methodInfo.ReturnType.FullName);

// retrive method parameters information
ParameterInfo [] paramInfos = methodInfo.GetParameters();
foreach (ParameterInfo paramInfo in paramInfos)
{
Console.WriteLine("Parameter Name: {0}, Parameter Type: {1}",
paramInfo.Name, paramInfo.ParameterType.FullName);
}
}
Console.ReadLine();
}


public void DoNothing()
{
}

public int Add(int x, int y)
{
return x + y;
}
}
}



A sample of the output follows:








Name: DoNothing, Public: True, Is Static: False, Return Type: System.Void

Name: Add, Public: True, Is Static: False, Return Type: System.Int32


Parameter Name: x, Parameter Type: System.Int32


Parameter Name: y, Parameter Type: System.Int32


Name: GetType, Public: True, Is Static: False, Return Type: System.Type


Name: ToString, Public: True, Is Static: False, Return Type: System.String


Name: Equals, Public: True, Is Static: False, Return Type: System.Boolean


Parameter Name: obj, Parameter Type: System.Object


Name: GetHashCode, Public: True, Is Static: False, Return Type: System.Int32




 



Technorati Tags: ,

No comments: