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

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

注意

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

注意

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

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

示例

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

using namespace System;
using namespace System::Reflection;

public ref 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, nullptr);
    }
};

int main()
{
    Asmload0::Main();
}
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);
    }
}
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

请参阅