Share via


如何:将程序集加载到应用程序域中

更新:2007 年 11 月

可以通过多种方式将程序集加载到应用程序域中。推荐方式是使用 System.Reflection.Assembly 类的 static(在 Visual Basic 中为 Shared)Load 方法。加载程序集的其他方式包括:

说明:

仅反射上下文是 .NET Framework 2.0 版中的新增功能。

  • 诸如 AppDomain 类的 CreateInstanceCreateInstanceAndUnwrap 之类的方法可以将程序集加载到应用程序域中。

  • Type 类的 GetType 方法可加载程序集。

  • System.AppDomain 类的 Load 方法可以加载程序集,但它主要用于实现 COM 互操作性。不应使用该方法将程序集加载到除从其调用该方法的应用程序域以外的其他应用程序域。

说明:

从 .NET Framework 2.0 版开始,对于版本号高于当前已加载运行库的 .NET Framework 版本,运行库将不加载由其进行编译的程序集。这同样适用于主版本号和次版本号的组合。

可以指定在应用程序域间共享来自已加载程序集的实时 (JIT) 编译代码的方式。有关更多信息,请参见应用程序域和程序集

示例

下面的代码将名为“example.exe”或“example.dll”的程序集加载到当前应用程序域中,从该程序集获取名为 Example 的类型,为该类型获取名为 MethodA 的无参数方法,然后执行该方法。有关从所加载程序集中获取信息的完整讨论,请参见动态加载和使用类型

Imports System
Imports System.Reflection

Public Class Asmload0
   Public Shared Sub Main()
      ' Use the file name to load the assembly into the current 
      ' application domain.
      Dim a As [Assembly] = [Assembly].Load("example")
      ' Get the type to use.
      Dim myType As Type = a.GetType("Example")
      ' Get the method to call.
      Dim mymethod As MethodInfo = myType.GetMethod("MethodA")
      ' Create an instance
      Dim obj As Object = Activator.CreateInstance(myType)
      ' Execute the method.
      mymethod.Invoke(obj, Nothing)
   End Sub 
End Class
using System;
using System.Reflection;

public class Asmload0
{
   public static void Main () 
   {
      // Use the file name to load the assembly into the current 
      // application domain.
      Assembly a = Assembly.Load("example");
      // Get the type to use.
      Type myType = a.GetType("Example");
      // Get the method to call.
      MethodInfo mymethod = myType.GetMethod("MethodA");
      // Create an instance.
      Object obj = Activator.CreateInstance(myType);
      // Execute the method.
      mymethod.Invoke(obj,null);
   }
}
using namespace System;
using namespace System::Reflection;

void main() 
{
   // Use the file name to load the assembly into the current 
   // application domain.
   Assembly^ a = Assembly::Load("example");
   // Get the type to use.
   Type^ myType = a->GetType("Example");
   // Get the method to call.
   MethodInfo^ mymethod = myType->GetMethod("MethodA");
   // Create an instance.
   Object^ obj = Activator::CreateInstance(myType);
   // Execute the method.
   mymethod->Invoke(obj,nullptr);
}

请参见

任务

如何:将程序集加载到仅反射上下文中

概念

对应用程序域进行编程

反射概述

应用程序域和程序集

参考

ReflectionOnlyLoad

其他资源

承载公共语言运行库

使用应用程序域