How to invoke a method at runtime using Reflection in c#?
Saturday, June 27, 2009
You need to call “InvokeMember” method of Reflection to do this.
Let us see this in detail with an example,
1. Create a Class library program and paste the code below,
Reflection Source Program
=========================
using System;
using System.Collections.Generic;
using System.Text;
namespace Employee
{
public class EmployeeDetails
{
private int empid=1;
private string empname="Ram";
private float salary=100000;
public string displayEmployeeDetails()
{
return "Empoyee Id:" + empid + "
" + "Empoyee Name:" + empname + "
" + "Empoyee salary:" + salary + "
";
}
}
}
2. compile it.
3. then create a windows application project and paste the following code
Reflection Program to invoke the method
==================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using Employee;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Assembly assembly = Assembly.LoadFrom("E:\\WebExperiments\\Employee\\Employee\\bin\\Debug\\Employee.dll");
foreach (Type type in assembly.GetTypes())
{
// Pick up a class
if (type.IsClass == true)
{
Console.WriteLine("...Found Class : {0}", type.FullName);
}
object ibaseObject = Activator.CreateInstance(type);
object result = null;
result = type.InvokeMember("displayEmployeeDetails",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
ibaseObject, null);
MessageBox.Show(result.ToString() );
}
}
}
}
4. add reference to the Employee dll
5. run the program and see the method invoked.
Subscribe to:
Post Comments (Atom)
0 comments
Post a Comment