Reputation: 1102
I have Tools.dll file that contains MyMethod() like this :
public void MyMethod()
{
global::System.Windows.Forms.MessageBox.Show("Sth");
}
Now , I am trying to run this assembly method from another file :
System.Reflection.Assembly myDllAssembly = System.Reflection.Assembly.LoadFile(@"PATH\Tools.dll");
myDllAssembly.GetType().GetMethod("MyMethod").Invoke(myDllAssembly, null); //here we invoke MyMethod.
After running 'System.NullReferenceException' happens . It says "Object reference not set to an instance of an object."
So How can I fix it ?!
Im sure this .dll building truth without problem .
Note : the assembly code come from : http://www.codeproject.com/Articles/32828/Using-Reflection-to-load-unreferenced-assemblies-a
Upvotes: 1
Views: 7268
Reputation: 2761
Remember, that 'Invoke' requires a class instance for non-static methods, therefore you should use construction like this:
Type type = myDllAssembly.GetType("TypeName");
type.GetMethod("MyMethod").Invoke(Activator.CreateInstance(type), null);
Class code:
public class MyClass
{
private string parameter;
/// <summary>
/// конструктор
/// </summary>
public MyClass(string parameter)
{
this.parameter = parameter;
}
public void MyMethod(string value)
{
Console.Write("You parameter is '{0}' and value is '{1}'", parameter, value);
}
}
Invokation code:
Type type = typeof(MyClass);
// OR
type = assembly.GetType("MyClass");
type.GetMethod("MyMethod").Invoke(Activator.CreateInstance(type, "well"), new object[] { "played" });
Result:
You parameter is 'well' and value is 'played'
Upvotes: 5
Reputation: 239794
You need to supply a name in your GetType(name)
call - at the moment, you're calling the standard GetType()
that every object implements and so you're getting the Assembly
type - and that doesn't have a MyMethod
method.
Upvotes: 2