.NET Framework 开发人员指南
如何:将程序集加载到应用程序域中

更新:2007 年 11 月

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

说明:

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

说明:

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

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

示例

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

Visual Basic
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
C#
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);
   }
}
Visual C++
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);
}
请参见

任务

概念

参考

其他资源

标记 :


Page view tracker