在外部程序中加载DLL?

时间:2012-01-20 17:39:17

标签: c# .net dll class-library

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

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

我想从外部的其他C#应用程序加载这个dll。我怎么能这样做?

4 个答案:

答案 0 :(得分: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

(来自here的翻译示例,但我写了所以不要担心!)

答案 1 :(得分:2)

建立在minitech的答案之上..如果你可以使用C#4.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);
    }

此处为instance类型的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);
    }

这将为您提供最佳表现。

答案 2 :(得分:-1)

右键单击Visual Studio中项目资源管理器中的引用,然后只需选择程序集。然后你可以使用它:

using ClassLibrary1;

class Program
{
    static void Main()
    {
        Calculator calc = new Calculator();
        int result = calc.Cal(1, 2);
    }
}

答案 3 :(得分:-1)

如果您使用visual studio,您可以在项目中引用此dll,而不是在新源代码中包含命名空间

相关问题