c# - 在外部程序中加载 DLL?

标签 c# .net dll class-library

我有一个 C# 类库,其中包含一个对两个数字求和的函数:

namespace ClassLibrary1
{
    public class Calculator
    {
        public int Calc(int i, int b) {
            return i + b;
        }
    }
}

我想从外部的其他 C# 应用程序加载此 dll。我该怎么做?

最佳答案

你的意思是你想通过文件名动态加载它?那么是的,您可以使用 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

(翻译自 here 的例子,但我写了所以别担心!)

关于c# - 在外部程序中加载 DLL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945537/

相关文章:

.net - 在Viewbox中获取TextBlock/Label进行缩放,而不会出现不必要的填充

c# - 线程.BeginThreadAffinity

c# - Azure 混合连接中的 SYSTEM_USER

c++ - 本地化在静态控制中不起作用

visual-studio-2010 - 在安装项目中包含文件依赖项

c# - 在 WPF 中处理来自 c++ dll 的未处理异常

c# - 如何检查一个值是否可以转换为泛型类型?

c# - 类型 'DateTime' 是在未引用的程序集中定义的?

c# - 如何使用 edmgen.exe 生成 .edmx.diagram 文件?

c# - 正则表达式替换为包含原始字符的字符串