Hi All,
A long time ago I researched Reflection and created a solution demoing my learnt capabilities from it.
In my example I did not pass any arguments into the Invocation of the method call using reflection.
I went to tackle this and I seem to be hitting a few dead ends.
Here is the method I call from my Main method in another class.
public void RunClass(string dllName, string className, string methodName, params Object[] parameters)
{
// Create the assemblies from our current DLL.
Assembly _Assemblies = Assembly.LoadFrom(dllName);
// Get the type that we want from the assemblies.
// IE: This would be the fully qualified class name (including namespace)
// Example: "Reflectionism.Examples.Example1" or "Reflectionism.Examples.Example2"
Type _Type = null;
try
{
_Type = _Assemblies.GetType(className);
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain classrd from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
return;
}
// Get the desired method we want from the target type.
MethodInfo _MethodInfo = null;
try
{
_MethodInfo = _Type.GetMethod(methodName, new Type[] { typeof(Object[]) });
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain method " + methodName + " from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
return;
}
// The first parameter to pass into the Invoke Method coming up.
Object _InvokeParam1 = Activator.CreateInstance(_Type);
//Object[] _Params = new Object[] { parameters };
// This calls the target method ("DisplayMyself").
// NOTE: I'm not passing any arguments down to the method being invoked.
// Therefore, I'm passing null as my argument, otherwise Invoke takes an
// array of Objects.
_MethodInfo.Invoke(_InvokeParam1, new Object[] { _parameters});
}
I call this RunClass method from my Main method like this:
//_UserInputParam is a Console.ReadLine() object (In my testing I am passing '5' to this call).
_Main._ReflectMain.RunClass(_UserInputDLL, _UserInputClass, _UserInputMethod, Int32.Parse(_UserInputParam));
The class that is being called by the invocation of the reflection method call is set up like this:
public void DisplayMyself(params Object[] parameters)
{
if (parameters.Length <= 0)
{
Console.WriteLine("Hello! I am " + this.ToString());
return;
}
Console.WriteLine("Parameter Found in: " + this.ToString() + "__ Param was: ");
for (int i = 0; i < parameters.Length; i++)
{
Console.WriteLine(parameters[i]);
}
}
The error I'm receiving is:
Object reference not set to instance of an object. It occurs on the line
And it occurs on the line:
_MethodInfo.Invoke(_InvokeParam1, new Object[] { parameters });
Even though when debugging parameters, it has the object '5' within it (or whatever the user inputs into the console.readline (and outputted through int32.parse() call).
Any help/insight would be appreciated.
Thanks,
-Catch