Visual C# 中的元件
以下是簡單字串元件在 Visual C# 中的樣子:
清單 1:Visual C# 中的元件 (CompCS.cs)
using System;
namespace CompCS {
public class StringComponent {
private string[] StringsSet;
public StringComponent() {
StringsSet = new string[] {
"C# String 0",
"C# String 1",
"C# String 2",
"C# String 3"
};
}
public string GetString(int index) {
if ((index < 0) || (index >=
StringsSet.Length)) {
throw new IndexOutOfRangeException();
}
return StringsSet[index];
}
public int Count {
get { return StringsSet.Length; }
}
}
}
前面曾提過,您必須使用 namespace 陳述式建立新的命名空間來封裝即將建立的類別:
namespace CompCS {
這個命名空間可為巢狀,而且可分成多個檔案。單一原始程式碼檔案也可包含多個非巢狀的命名空間。由於所有 Visual C# 程式碼都必須包含在類別中,因此需要有包含命名空間。
public class StringComponent {
StringComponent 的執行個體將由 Common Language Runtime 建立,並且在記憶體回收堆積中管理。每次建立新類別執行個體時所執行的類別建構函式具有和類別相同的名稱,而且沒有傳回型別。
public StringComponent() {
由於 Visual C# 只使用 Managed 型別,因此您在宣告時不必做任何處理,這點和在 Managed Extensions for C++ 中不同。
以下是 GetString 方法,它會接受整數引數並傳回字串,在這三種範例語言中都很簡單而且是相同的:
public string GetString(int index) {
...
return StringsSet[index];
}
請注意 GetString 方法中的 throw 陳述式:
throw new IndexOutOfRangeException();
這個陳述式會建立並擲回 IndexOutOfRangeException 型別的 Runtime 架構例外處理物件。
最後,您會建立唯讀的 Length 屬性:
public int Count {
get { return StringsSet.Length; }
}
Visual C# 元件的編譯程序只比獨立 (Stand-Alone) 程式略微複雜一些:
csc.exe /t:library /debug+ /out:..\bin\CompCS.dll CompCS.cs
和 Managed Extensions for C++ 元件一樣,您也是使用 /out 參數將編譯完的元件放在 ..\Bin 子目錄中。同樣地,您需要用 /t(arget):library 參數建立 DLL,而非具有 .dll 副檔名的可執行檔。