【问题标题】:Loading DLL in external program?在外部程序中加载 DLL?
【发布时间】:2012-02-15 06:17:27
【问题描述】:

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

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

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

【问题讨论】:

  • 如果你使用visual studio:添加引用,然后搜索你的dll
  • 你读过一些关于 .NET/C# 基础的东西吗?
  • 为什么会被否决?它可能不像看起来那么明显(无论如何都是显而易见的);请参阅@minitech 的回答。

标签: c# .net dll class-library


【解决方案1】:

您的意思是要通过文件名动态加载它吗?那么是的,你可以使用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翻译的例子,但我写的,所以不用担心!)

【讨论】:

    【解决方案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);
        }
    

    这里作为dynamic类型的instance,你不必通过反射找到方法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);
        }
    

    这将为您提供最佳性能。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        如果你使用 Visual Studio,你可以在你的项目中引用这个 dll,而不是在你的新源代码中包含命名空间

        【讨论】:

          猜你喜欢
          • 2017-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多