Search This Blog

2010/01/17

Invoking Method Using Reflection:

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

namespace Reflection_to_Invoke_Method_in_csharp
{
class Program
{
static void Main(string[] args)
{
Type t = typeof(MyMath);
MyMath XMath = new MyMath();

MethodInfo[] M = t.GetMethods();

foreach (MethodInfo m in M )
{
ParameterInfo[] P = m.GetParameters();
if (m.Name.CompareTo("Add")==0)
{
if (P[0].ParameterType == typeof(int))
{
if (P[1].ParameterType == typeof(int))
{
object[] orgs = new object[2];
orgs[0] = 56;
orgs[1] = 23;
double res= Convert.ToDouble( m.Invoke(XMath, orgs));
Console.WriteLine("56+23="+res.ToString());

}
}
}
}
Console.ReadKey();
}
}
public class MyMath
{
public Double Add(int x,int y)
{
return x + y;

}
public Double Substract(int x, int y)
{
return Add(x, -y);

}
public Double Multiply(int x, int y)
{
return x*y;

}
public Double Divide(int x, int y)
{
return x/y ;
}


}
}

No comments:

Post a Comment