共用方式為


Managed Extensions for C++ 中的用戶端

以下是用戶端在 Managed Extensions for C++ 中的樣子:

清單 1:Managed Extensions for C++ 中的用戶端 (ClientVC.cpp)

#using <mscorlib.dll>
using namespace System;

#using "..\Bin\CompCS.dll"
#using "..\Bin\CompVC.dll"
#using "..\Bin\CompVB.dll"

// The method, main, is the application's entry point.
void main() {

   // Iterate through the component's strings,
   // and write them to the console.
   CompCS::StringComponent* myCSStringComp = 
      new CompCS::StringComponent();
   Console::WriteLine  
      (L"Strings from C# StringComponent");
   for (int index = 0; index < myCSStringComp->Count; 
      index++) {
      Console::WriteLine(myCSStringComp-> 
         GetString(index));
   }

   // Iterate through the component's strings,
   // and write them to the console.
   CompVC::StringComponent* myVCStringComp = 
      new CompVC::StringComponent();
   Console::WriteLine 
     (L"\nStrings from Visual C++ StringComponent");
   for (int index = 0; index < myVCStringComp->Count; 
      index++) {
      Console::WriteLine(myVCStringComp-> 
   GetString(index));
   }

   // Iterate through the component's strings,
   // and write them to the console.
   CompVB::StringComponent* myVBStringComp = 
      new CompVB::StringComponent();
   Console::WriteLine(L"\nStrings from Visual Basic 
      StringComponent");
   for (int index = 0; index < myVBStringComp->Count; 
      index++) {
      Console::WriteLine(myVBStringComp-> 
   GetString(index));
   }
}

首先要注意的是三個元件的匯入方式,每一個元件目前都是位於適當的 ..\Bin 子目錄中:

#using "..\Bin\CompCS.dll"
#using "..\Bin\CompVC.dll"
#using "..\Bin\CompVB.dll"

除了所要使用的程式庫指定以外,呼叫這三個字串元件的用戶端程式碼區段完全相同。這三個區段中的第一個陳述式都是宣告 StringComponent 型別 (在元件定義) 的新區域變數、初始化變數,以及呼叫它的建構函式:

CompCS::StringComponent* myCSStringComp = 
new CompCS::StringComponent();

將字串寫入主控台來表示這個部份的程式已輸入之後,用戶端就會使用 Count 屬性的值重複適當字串元件的成員:

for (int index = 0; index < myCSStringComp->Count; 
    index++) {
    Console::WriteLine(myCSStringComp-> 
 GetString(index));
}

說明到此為止,另外兩個語言元件都是重複同樣的方式。

**注意   **如果您使用索引子 (Indexer) 方式,而非單獨的 GetString 方法,myCSStringComp[index] 呼叫程式碼就會比較自然。

建置新的 Managed Extensions for C++ 用戶端很簡單:

cl.exe /clr /Zi /c ClientVC.cpp
link.exe /debug /nod:libcpmt.lib 
    kernel32.lib mscoree.lib 
    /out:..\bin\ClientVC.exe ClientVC.obj

和前面的 Managed Extensions for C++ 範例一樣,您也需要用 /CLR 參數指示編譯器建立 Common Language Runtime Managed 程式碼。執行產生的程式會得到下列結果:

C:\...\CompTest\Bin>clientvc
Strings from C# StringComponent
C# String 0
C# String 1
C# String 2
C# String 3

Strings from Visual C++ StringComponent
Visual C++ String 0
Visual C++ String 1
Visual C++ String 2
Visual C++ String 3

Strings from Visual Basic StringComponent
Visual Basic String 0
Visual Basic String 1
Visual Basic String 2
Visual Basic String 3

請參閱

Visual C# 中的用戶端 | Visual Basic 中的用戶端 | 使用 Windows Form 的 Windows 用戶端 | 使用 ASP.NET 的用戶端 | 開發教學課程摘要 | 附錄 A:瀏覽命名空間的工具