共用方式為


在其他應用程式定義域中執行程式碼 (C# 程式設計手冊)

更新:2007 年 11 月

組件一載入到應用程式定義域後,即可執行其中所包含的程式碼。若要執行這項作業,最簡單的方式是使用 AssemblyLoad,這個關鍵字會將組件載入到目前的應用程式定義域,並從組件的預設進入點開始執行程式碼。

如果您想將組件載入至另一個應用程式定義域,請使用 ExecuteAssemblyExecuteAssemblyByName,或這些方法之其他多載版本中的其中一個。

如果您要執行的組件不是從預設進入點啟動,則請在該遠端組件中定義一個新型別,並使用 MarshalByRefObject 衍生這個新型別。然後再使用 CreateInstance 在應用程式中建立這個型別的執行個體。

以下列檔案為例,這個檔案會建立包含單一命名空間和兩個類別的組件。假設這個組件已經建立,並以 HelloWorldRemote.exe 的名稱儲存在 C 磁碟中。

// This namespace contains code to be called.
namespace HelloWorldRemote
{
    public class RemoteObject : System.MarshalByRefObject
    {
        public RemoteObject()
        {
            System.Console.WriteLine("Hello, World! (RemoteObject Constructor)");
        }
    }
    class Program
    {
        static void Main()
        {
            System.Console.WriteLine("Hello, World! (Main method)");
        }
    }
}

若要從另一個應用程式存取程式碼,您可以將組件載入到目前的應用程式定義域,或建立一個新的應用程式定義域,再將組件載入到這個新應用程式定義域中。如果您使用 Assembly.LoadFrom 將組件載入到目前的應用程式定義域,則可以使用 Assembly.CreateInstance 來產生 RemoteObject 類別的執行個體,讓物件建構函式開始執行。

static void Main()
{
    // Load the assembly into the current appdomain:
    System.Reflection.Assembly newAssembly = System.Reflection.Assembly.LoadFrom(@"c:\HelloWorldRemote.exe");

    // Instantiate RemoteObject:
    newAssembly.CreateInstance("HelloWorldRemote.RemoteObject");
}

當組件載入到獨立的應用程式定義域時,可以使用 AppDomain.ExecuteAssembly 來存取預設進入點,或使用 AppDomain.CreateInstance 來建立 RemoteObject 類別的執行個體。建立執行個體會讓建構函式開始執行。

static void Main()
{
    System.AppDomain NewAppDomain = System.AppDomain.CreateDomain("NewApplicationDomain");

    // Load the assembly and call the default entry point:
    NewAppDomain.ExecuteAssembly(@"c:\HelloWorldRemote.exe");

    // Create an instance of RemoteObject:
    NewAppDomain.CreateInstanceFrom(@"c:\HelloWorldRemote.exe", "HelloWorldRemote.RemoteObject");
}

如果您不想以程式設計方式載入組件,可以使用 [方案總管] 的 [加入參考] 來指定組件 HelloWorldRemote.exe。然後,將 using HelloWorldRemote; 陳述式加入至應用程式的使用區塊,並使用程式中的 RemoteObject 型別宣告 RemoteObject 物件的執行個體,如下所示:

static void Main()
{
    // This code creates an instance of RemoteObject, assuming HelloWorldRemote has been added as a reference:
    HelloWorldRemote.RemoteObject o = new HelloWorldRemote.RemoteObject();
}

請參閱

概念

C# 程式設計手冊

應用程式定義域概觀

應用程式定義域和組件

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

參考

應用程式定義域 (C# 程式設計手冊)

其他資源

應用程式定義域

使用應用程式定義域和組件設計程式