Hi guys!
I have learned before, how to use reflection to call a method from another dll file, but I was wodering if it's possible to create an instance of a class in another dll through reflection?`?
blah blah blah is here! blah blah » Close
1 answers
I know very little (see: nothing) about reflection, but I suppose you could call a method that creates an instance of a class :)
answered 2 years ago by:
2499
Thanks man, Of course!. :)
answered 2 years ago by:
66
To create an instance of a type using reflection, check out the <a target="_new" href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx">Activator.CreateInstance</a> method.
answered 2 years ago by:
17279
Ok now, I can't see how that method knows which assembly I'm trying to connect to. Or which namespace. ??
answered 2 years ago by:
66
OK, here's a quick example.
Suppose you have this dll (test.dll say):
using System;
namespace Test
{
public class MyClass
{
public void MyMethod()
{
Console.WriteLine("Hello from Test.MyClass!");
}
}
}
and you want to create an instance of Test.MyClass and then call MyMethod() from another program using reflection.
Here's how to do it (I've used Assembly.CreateInstance rather than Activator.CreateInstance here):
using System;
using System.Reflection;
namespace Program
{
class MyProgram
{
static void Main()
{
Assembly assembly = Assembly.LoadFrom("test.dll");
object mc = assembly.CreateInstance("Test.MyClass");
Type t = mc.GetType();
MethodInfo mi = t.GetMethod("MyMethod");
mi.Invoke(mc, null);
Console.ReadKey();
}
}
}
answered 2 years ago by:
17279
This post was imported from csharpfriends, if you have a similiar question please ask it again.
All previous members have been migrated, hope you enjoy the new platform!