Share via


HOW TO:將組件載入應用程式定義域

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

注意事項注意事項

僅限反映的內容是 .NET Framework 2.0 版中所新增。

  • 類似 AppDomain 類別的 CreateInstanceCreateInstanceAndUnwrap 方法,可以將組件載入應用程式定義域中。

  • Type 類別的 GetType 方法可載入組件。

  • System.AppDomain 類別的 Load 方法可以載入組件,但主要用於 COM 互通性 (Interoperability)。 您不應該使用這個方法將組件載入呼叫此方法之應用程式定義域以外的應用程式定義域中。

注意事項注意事項

從 .NET Framework 2.0 版開始,如果使用比目前載入之執行階段版本還要高的 .NET Framework 版本來編譯組件,則執行階段將不會載入這個組件。這種情形適用於版本號碼的主要和次要元件組合。

您可以指定 Just-in-Time (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;

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();
}

請參閱

工作

HOW TO:將組件載入僅限反映的內容

參考

ReflectionOnlyLoad

概念

裝載概觀

使用應用程式定義域設計程式

反映

應用程式定義域和組件

其他資源

使用應用程式定義域