C# 在外部程序中加载DLL?
我有一个C类库,它包含一个函数来求两个数的和:C# 在外部程序中加载DLL?,c#,.net,dll,class-library,C#,.net,Dll,Class Library,我有一个C类库,它包含一个函数来求两个数的和: namespace ClassLibrary1 { public class Calculator { public int Calc(int i, int b) { return i + b; } } } 我想从其他C应用程序外部加载此dll。如何执行此操作?在Visual Studio中的项目资源管理器中的引用上单击鼠标右键,然后简单地选择程序集。然后您可以使用它
namespace ClassLibrary1
{
public class Calculator
{
public int Calc(int i, int b) {
return i + b;
}
}
}
我想从其他C应用程序外部加载此dll。如何执行此操作?在Visual Studio中的项目资源管理器中的引用上单击鼠标右键,然后简单地选择程序集。然后您可以使用它:
using ClassLibrary1;
class Program
{
static void Main()
{
Calculator calc = new Calculator();
int result = calc.Cal(1, 2);
}
}
如果您使用visual studio,您可以在项目中引用此dll,然后在新的源代码中包含名称空间您的意思是要按文件名动态加载它吗?那么是的,您可以使用以下方法:
// 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
翻译的例子,但我写的,所以不要担心 根据minitech的答案。。如果可以使用C4.0,则可以省略一些反射调用
public static void Main()
{
Assembly ass = Assembly.LoadFile(@"PathToLibrar\ClassLibraryTest.dll");
var type = ass.GetType("ClassLibrary1.Calculator");
dynamic instance = Activator.CreateInstance(type);
int add = instance.Calc(1, 3);
}
这里作为dynamic类型的实例,您不必通过反射找到Calc方法
但最好的方法是在上游定义一个接口
public interface ICalculator
{
int Calc(int i, int b);
}
并在您的类中实现它
public class Calculator : ICalculator
{
public int Calc(int i, int b)
{
return i + b;
}
}
然后你可以用最少的反射来构造这个对象
public static void Main()
{
Assembly ass = Assembly.LoadFile(@"PathToLibrar\ClassLibraryTest.dll");
var type = ass.GetType("ClassLibrary1.Calculator");
ICalculator instance = Activator.CreateInstance(type) as ICalculator;
int add = instance.Calc(1, 3);
}
这将为您提供最佳性能。如果您使用visual studio:添加引用,然后搜索您的DLLD,您是否阅读过有关.NET/C基础知识的内容?为什么会被否决?它可能不像看上去那么明显;请参阅@minitech的答案。