Calling function dynamically by using Reflection
Posted
by Alaa'
on Stack Overflow
See other posts from Stack Overflow
or by Alaa'
Published on 2010-05-10T18:28:49Z
Indexed on
2010/05/10
18:34 UTC
Read the original article
Hit count: 304
c#
|reflection
Hi, I'm generating dll files contain code like the following example : // using System; using System.Collections; using System.Xml; using System.IO; using System.Windows.Forms;
namespace CSharpScripter { public class TestClass : CSharpScripter.Command {
private int i=1; private int j=2; public int k=3;
public TestClass6() {
} public void display (int i,int j,int k) {
string a = null;
a= k.ToString();
string a1 = null;
a1= this.i.ToString();
string a2 = null;
a2= j.ToString();
MessageBox.Show(" working! "+ "k="+ a +" i="+a1 + " j="+ a2);
} public void setValues(int i,int j,int k1) { this.i=i; this.j=j; k=k1; } // I'm compiling the pervious code, then I execute an object from the dll file. So, in the second part of the code ( Executing part), I'm just calling the execute function, It contains a call for a function, I named here: display. For that I need to set values in the declaration by a setValue function. I want it to been called dynamically (setValues ), which has declaration like : public void(Parameter[] parameters) { //some code block here }
For this situation I used Reflection. // Type objectType = testClass.GetType(); MethodInfo members = objectType.GetMethod("setValues");
ParameterInfo[] parameters = members.GetParameters();
For) int t = 0; t < parameters.Length; t++)
{
If (parameters[t]. ParameterType == typeof())
{
object value = this.textBox2.Text;
parameters.SetValue)Convert.ChangeType(value,parameters[t].ParameterType), t);
}
}
// But it throws an casting error" Object cannot be stored in an array of this type." at last line, in first parameter for (setValue) methode. What is the problem here? And How I can call the method Dynamically after the previous code, by( Invoke) or is there a better way?
Thanks.
© Stack Overflow or respective owner