HOW TO:將組件載入應用程式定義域
更新:2007 年 11 月
將組件載入應用程式定義域的方式有好幾種,建議的方式是使用 System.Reflection.Assembly 類別的 static (在 Visual Basic 中為 Shared) Load 方法。載入組件的其他方式包括:
ReflectionOnlyLoad 和 ReflectionOnlyLoadFrom 方法可將組件載入僅限反映的內容中。載入此內容中的組件可以進行檢查但不能加以執行,以允許檢查以其他平台為目標的組件。請參閱 HOW TO:將組件載入僅限反映的內容。
![]() |
---|
僅限反映的內容是 .NET Framework 2.0 版中所新增。 |
類似 AppDomain 類別的 CreateInstance 和 CreateInstanceAndUnwrap 方法,可以將組件載入應用程式定義域中。
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;
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);
}