作法:將組件載入應用程式定義域

有數種方式可以將組件載入應用程式定義域。 建議的方法是使用 System.Reflection.Assembly 類別的 static (在 Visual Basic 中為 Shared) Load 方法。 其他可以載入組件的方式包括:

注意

僅限反映的內容是 .NET Framework 2.0 版的新功能。

注意

從 .NET Framework 2.0 版開始,執行階段不會載入使用 .NET Framework 版本所編譯的組件,而這個版本的版本號碼高於目前載入的執行階段。 這適用於版本號碼的主要與次要元件組合。

您可以指定在應用程式定義域之間共用所載入組件之 Just-In-Time (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

另請參閱