在外部程序中加载DLL?

Ahm*_*her 4 .net c# dll class-library

我有一个C#ClassLibrary,它包含一个对两个数字求和的函数:

namespace ClassLibrary1
{
    public class Calculator
    {
        public int Calc(int i, int b) {
            return i + b;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想从外部的其他C#应用程序加载此DLL.我怎样才能做到这一点?

Ry-*_*Ry- 12

你的意思是你想通过文件名动态加载吗?然后是的,你可以使用Assembly.LoadFile如下方法:

// Load the assembly
Assembly a = Assembly.LoadFile(@"C:\Path\To\Your\DLL.dll");

// Load the type and create an instance
Type t = a.GetType("ClassLibrary1.Calculator");
object instance = a.CreateInstance("ClassLibrary1.Calculator");

// Call the method
MethodInfo m = t.GetMethod("Calc");
m.Invoke(instance, new object[] {}); // Get the result here
Run Code Online (Sandbox Code Playgroud)

(从这里翻译的例子,但我写了所以不要担心!)