Visual C# 中的用戶端
以下是用戶端在 Visual C# 中的樣子:
清單 1:Visual C# 中的用戶端 (ClientCS.cs)
using System;
using CompVC;
using CompCS;
using CompVB;
// This class exists to house the application's entry point.
class MainApp {
// The static method, Main, is the application's entry point.
public static void Main() {
// Iterate through the component's strings,
// and write them to the console.
CompCS.StringComponent myCSStringComp = new
CompCS.StringComponent();
Console.WriteLine("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("\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("\nStrings from Visual Basic
StringComponent");
for (int index = 0; index < myVBStringComp.Count;
index++) {
Console.WriteLine(myVBStringComp.GetString(index));
}
}
}
和 Managed Extensions for C++ 範例不同,這時候您不需要匯入程式庫。相反地,您可以在編譯程序中指定程式庫。透過 using 陳述式指定程式庫的優點是,using 會將命名空間合併到程式中,讓您不需要使用完整的型別名稱即可參考程式庫中的型別。由於所有範例元件都具有相同的型別名稱 (StringComponent),因此在參考所有元件都通用的方法 (GetString) 和屬性 (Count) 時,仍然必須使用完整名稱來避免混淆。
Visual C# 還提供了一個稱為別名的機制來解決這個問題。如果將 using 陳述式變更成下列陳述式,就不需要使用完整名稱:
using VCStringComp = CompVC.StringComponent;
using CSStringComp = CompCS.StringComponent;
using VBStringComp = CompVB.StringComponent;
除了範圍解析運算子以外,這個用戶端程式碼實際上和 Managed Extensions for C++ 範例完全相同。而且,除了所要使用的程式庫指定以外,呼叫這三個字串元件的程式碼也相同。和 Managed Extensions for C++ 範例一樣,這三個區段中的第一個陳述式都是宣告 StringComponent 型別的新區域變數、初始化變數,以及呼叫它的建構函式:
CompCS.StringComponent myCSStringComp = new
CompCS.StringComponent();
將字串寫入主控台來表示這個部份的程式已輸入之後,用戶端就會使用 Count 屬性的值重複適當字串元件的成員:
for (int index = 0; index < myVCStringComp.Count;
index++) {
Console.WriteLine(myVCStringComp.GetString(index));
}
說明到此為止,另外兩個語言元件都是重複同樣的方式。
建置新的 Visual C# 用戶端很簡單。由於您現在是使用自己的 ..\Bin 子目錄中的元件,因此需要使用 /reference 編譯參數,將它們明確包含在內:
csc.exe /debug+ /reference:..\Bin\CompCS.dll;
..\Bin\CompVB.dll;..\Bin\CompVC.dll
/out:..\Bin\ClientCS.exe ClientCS.cs
此外,由於您正在建置的是用戶端程式,而非可從其他程式呼叫的元件,因此不需要使用 /t 參數。
除此之外,這個程序和前面的 Visual C# 範例相同。執行產生的程式會得到下列結果:
C:\...\CompTest\Bin>clientcs
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 Basic 中的用戶端 | 使用 Windows Form 的 Windows 用戶端 | 使用 ASP.NET 的用戶端 | 開發教學課程摘要 | 附錄 A:瀏覽命名空間的工具