Created
November 16, 2015 09:11
-
-
Save redknitin/7e593e507d8d39aefb97 to your computer and use it in GitHub Desktop.
Dynamically load DLL in .NET
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //This is in LibFunctions.dll | |
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace LibFunctions | |
| { | |
| public class InstanceThing | |
| { | |
| public int Sum(int a, int b) { return a + b; } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //This is in LoadWithReflection.exe | |
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| using System.Reflection; | |
| namespace LoadWithReflection | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| Assembly Lib = Assembly.LoadFrom("LibFunctions.dll"); | |
| Type instanceThingType; | |
| Type staticThingType; | |
| Object instanceThingObject; | |
| if (null != (instanceThingType = Lib.GetType("LibFunctions.InstanceThing"))) | |
| { | |
| instanceThingObject = Activator.CreateInstance(instanceThingType); | |
| MethodInfo mi = instanceThingType.GetMethod("Sum"); | |
| object resultI = mi.Invoke(instanceThingObject, new object[] { 1, 2 }); | |
| Console.WriteLine(resultI.ToString()); | |
| } | |
| else { Console.WriteLine("Type not found"); } | |
| if (null != (staticThingType = Lib.GetType("LibFunctions.StaticThing"))) | |
| { | |
| MethodInfo ms = staticThingType.GetMethod("Sum"); | |
| object resultS = ms.Invoke(null, new object[] { 3, 4 }); | |
| Console.WriteLine(resultS.ToString()); | |
| } | |
| else { Console.WriteLine("Type not found"); } | |
| Console.WriteLine("Finished"); | |
| Console.Read(); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //This is in LibFunctions.dll | |
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| namespace LibFunctions | |
| { | |
| public static class StaticThing | |
| { | |
| public static int Sum(int a, int b) { return a + b; } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment