Why does it always seem that when I post C# threads, I'm only talking to myself? In any case, I've hit my first snag. I've reached the point where I want to invoke a public, static method that's defined in the current class. All the System.Reflection examples I've found are for invoking methods from a different class, or an assembly, or on instance objects. How do you invoke a STATIC (ie, "class method") method of the CURRENT class?
Code:
using System;
using System.IO;
using System.Collections;
using System.Reflection;
namespace pcl_util
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static string filename;
static string function;
static FileStream baseFS;
[STAThread]
static void Main(string[] args)
{
// get filename to process, if found, declare a FileStream
filename = args[0].ToString();
if (File.Exists(filename))
{
baseFS = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 8192);
}
else
{
Console.WriteLine("FILE NOT FOUND: " + filename);
}
// does function exist in this program? If so, get its parameters and run it
function = args[1].ToString();
if (checkFunction(function))
{
Type myType = typeof(Class1);
MethodInfo myMethodInfo = myType.GetMethod(function);
ParameterInfo[] myParameters = myMethodInfo.GetParameters();
// collect parameters, call method.
object[] methodParams = new Object [myParameters.Length];
int mpIndex = 0;
foreach( ParameterInfo paramInfo in myParameters)
{
if (paramInfo.ParameterType == Type.GetType("System.IO.FileStream"))
{
methodParams[mpIndex] = baseFS;
}
mpIndex++;
}
myType.InvokeMember(function,
BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.InvokeMethod, null, null, methodParams);
}
else
{
Console.WriteLine("FUNCTION NOT FOUND: " + function);
}
}
public static bool checkFunction(string f)
{
Type myType = typeof(Class1);
MethodInfo myMethodInfo = myType.GetMethod(f);
if (myMethodInfo == null)
{
return false;
}
else
{
return true;
}
}
public static System.Int32 getFF(FileStream fs)
{
// get the byte position of all FF in file
Console.WriteLine("getFF ran.");
return 0;
}
}
}
The problem is in the InvokeMethod() method. The second "null" in the parameter list is supposed to be an object. What object? The only object is the currently running instance of the current class. I'm confused.
For the command line arguments, I'm passing in a valid filename, and the string "getFF". The above code is supposed to invoke the getFF() method.