sunwen教程之----c#進階
(五)
[email protected]
大家好,我是武漢華師的sunwen.我回來了.現在是五月二號下午3:20.我剛從電腦城回來,買了一版d版的mp3.嗚,湖北的同學都回去了,尤其是武漢的,跑得特別快,真是可恨.剩下我一個孤零零的福建佬,沒事做,只好一個人聽音樂,真是慘!幸好這音樂還比較好聽,呵呵,其實sunwen一點音樂細胞也沒有.
言歸正傳,我現在要說的是庫(libraries),和大家一起學習如何用c#建立一個dll文件.說起dll,肯定是無人不知,無人不曉,這個windows的典型代表,同時也經常是大家功擊的對象.呵呵,不管怎么樣,學還是要學的.我們下面就開始,如何用命令行方式將一個c#程序編譯成dll,和如何在客戶端使用他.
這個例子包括兩個文件,一個是factorial.cs,作用是計算一個數字的階乘.還有一個是digitcounter.cs,作用是計算傳過來的字符串參數中的數字的數目.
我們可以這樣來建立庫,在命令行方式下這樣做:
csc /target:library /out:functions.dll factorial.cs digitcounter.cs
下面講一下各個參數的用法:
/target:library:向系統指出輸出的是一個dll庫,而不是一個exe的可執行文件.
/out:functions.dll:指定輸出的dll的文件名,即functions.dll,一般地,如果你省略了第一個參數,那么默認的文件名將是第一個文件的文件名,即factorial.dll.
下面我們再來建立一個文件,即使用這個庫的文件,叫客戶端文件,functionclient.cs.建立好后,用下面的語名編譯:
csc /out:functiontest.exe /r:functions.dll functionclient.cs
下面說一下這個編譯語句的用法:
/out:functiontest.exe:指出輸出的文件名是functiontest.exe
/r:functions.dll:指出要引用的庫,如果不是在當前目錄下,必須要指出其的完整路徑.
下面我就把這幾個文件的代碼寫在下面:
000: // libraries/factorial.cs
001: using system;
002:
003: namespace functions
004: {
005: public class factorial
006: {
007: public static int calc(int i)
008: {
009: return((i <= 1) ? 1 : (i * calc(i-1)));
010: }
011: }
012: }
這是factorial.cs這個文件的代碼.在003行中,namespace的意思是名字空間,據m$的介紹,庫必須根據它的名字空間打包,以使.net能夠正確地載入你的類.
下面是digitcounter.cs這個文件的內容:
000: // libraries/digitcounter.cs
001: using system;
002:
003: namespace functions
004: {
005: public class digitcount
006: {
007: public static int numberofdigits(string thestring)
008: {
009: int count = 0;
010: for ( int i = 0; i < thestring.length; i++ )
011: {
012: if ( char.isdigit(thestring[i]) )
013: {
014: count++;
015: }
016: }
017:
018: return count;
019: }
020: }
021: }
注意,這個例子中的namespace應與第一個的一致,因為它們是同一個庫中的.numberofdigits方法計算了參數中的數字的個數.
第三個文件是functionclient.cs
我們知道,一個庫一旦建立,就可以被別的類利用(廢話,要不然怎么叫庫呢?).下面的c#程序就利用了我們剛才建立的庫中的類.
000: // libraries/functionclient.cs
001: using system;
002: using functions;
003: class functionclient
004: {
005: public static void main(string[] args)
006: {
007: console.writeline("function client");
008:
009: if ( args.length == 0 )
010: {
011: console.writeline("usage: functiontest ... ");
012: return;
013: }
014:
015: for ( int i = 0; i < args.length; i++ )
016: {
017: int num = int32.parse(args[i]);
018: console.writeline(
019: "the digit count for string [{0}] is [{1}]",
020: args[i],
021: digitcount.numberofdigits(args[i]));
022: console.writeline(
023: "the factorial for [{0}] is [{1}]",
024: num,
025: factorial.calc(num) );
026: }
027: }
028: }
在002行中,一個using functions指明了引用functions.dll這個類.
如果我們在命令行中鍵入如下命令,就可以看到輸出:
functiontest 3 5 10
輸出:
function client
the digit count for string [3] is [1]
the factorial for [3] is [6]
the digit count for string [5] is [1]
the factorial for [5] is [120]
the digit count for string [10] is [2]
the factorial for [10] is [3628800]
注意:當你運行這個.exe文件時,它引用的dll文件可以是在當前目錄,子目錄,或是corpath這個環境變量.corpath這個環境變量是在.net環境中的類路徑,用來指引系統尋找類.說白了,就是java中的classpath,明白了吧,呵呵.
好了,又完了一篇,今天的任務完成了,可以休息了.唉,有什么好玩的呢?
下一頁