I have a method as shown below…
public bool MakeRequest(string[] args)
{
try
{
sXmlRequest = args[0];
sResponse = "";
Console.WriteLine(sXmlRequest);
sw.Write(sXmlRequest);
sw.Flush();
sResponse = sr.ReadToEnd();
return true;
}
catch (Exception e)
{
sResponse = e.Message;
return false;
}
}
I have to call this method using Reflection, because of the way the entire framework is setup.
Here is the code I’m using to call it
string[] innerargs = {"Dummy Args"};
string pAssembly = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\TCPConnector.dll";
Assembly assemblyInstance = Assembly.LoadFrom(pAssembly);
Type tConnector = assemblyInstance.GetType("Fit.TcpConnector");
Object oLateBound = assemblyInstance.CreateInstance(tConnector.FullName);
result = tConnector.InvokeMember("MakeRequest", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, oLateBound, innerargs);
This is returning me MissingMethodException saying the method Fit.TcpConnector.MakeRequest is not found.
However, if I change the signature of the MakeRequest to
public bool MakeRequest(string args)
instead of
public bool MakeRequest(string[] args)
then, it is working. Can anybody point me in right direction in calling the function which takes array as its parameter?
You have to pass it an array that contains your array:
That’s because each item in the array you pass to the method represents one parameter to the function. And since you function has one parameter of type
string[], you need to give it an array that contains one item of typestring[].That being said, I think using
GetMethod()andInvoke()is clearer thanInvokeMember():Your incorrect code compiles because of array covariance as Eric Lippert pointed out in his answer.