首頁  >  文章  >  後端開發  >  SUNWEN教程之----C#進階(五)

SUNWEN教程之----C#進階(五)

黄舟
黄舟原創
2016-12-19 10:20:281041瀏覽

我現在要說的是庫(libraries),和大家一起學習如何用C#建立一個DLL檔.說起DLL,肯定是無人不知,無人不曉,這個WINDOWS的典型代表,同時也經常是大家功擊的對象.呵呵,不管怎麼樣,學還是要學的.我們下面就開始,如何用命令行方式將一個C#程式編譯成DLL,和如何在客戶端使用他.

這個例子包括兩個檔,一個是Factorial.cs,作用是計算一個數字的階乘.還有一個是DigitCounter.cs,作用是計算傳過來的字符串參數中的數字的數目.

我們可以這樣來建立庫,在命令列方式下這樣做:
csc /target:library /out:Functions.dll Factorial.cs DigitCounter.cs

下面講一下各個參數的用法:

/target:library:向系統指出輸出的是一個參數的用法:

/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. Functions.DLL:指出要引用的庫,如果不是在當前目錄下,必須要指出其的完整路徑.


下面我就把這幾個文件的代碼寫在下面:


000: // LibrariesFactorial. cs
001: using System; 
002: 
003: namespace Functions 
004: { 
005: public class Factorial 
006: { 
007:public class Factorial 
006: { 9: return(( i 010: } 
011: }
012: }
這是Factorial.cs這個檔案的程式碼.在003行,namespace的意思是名字空間,根據M$的介紹,庫必鬚根據它的名字空間打包,以使.NET能夠正確地載入你的類.

下面是DigitCounter.cs這個文件的內容:

000: / / LibrariesDigitCounter.cs
001: using System; 
002: 
003: namespace Functions 
004: { 
005: public class DigitCount 
006: 
005: public class DigitCount 
006: 
008: { 
009: int count = 0; 
010: for ( int i = 0; i 011: { 
012: if ( Char.IsDigit(theString[i]) ) 
013: if ( Char.IsDigit(theString[i]) ) 
013:01 ; 
015: } 
016: } 
017: 
018: return count; 
019: } 
020: }
021: }

空間一個庫中的.NumberOfDigits方法計算了參數中的數字的個數.

第三個檔案是FunctionClient.cs


我們知道,一個庫一旦建立,就可以被別的類利用(廢話,要不然怎麼叫庫呢?).下面的C#程式就利用了我們剛才建立的函式庫中的類別.


000: // LibrariesFunctionClient.cs
001: using System; 
002: using Functions;
003: class Function 004: { 
005: public static void Main(string[] args) 
006: { 
007: Console.WriteLine("Function Client"); 
008: 🜎 : {
011: Console.WriteLine("Usage: FunctionTest ... "); 
012: return; 
013: } 
014: 
015: for ( int i = 0; 016: { 
017: int num = Int32.Parse(args[i]); 
018: Console.WriteLine(
019: "The Digit Count for String [{0}] is [{1}]", : args[i], 
021: DigitCount.NumberOfDigits(args[i])); 
022: Console.WriteLine(
023: "The Factorial for [{0}] is [{1}]
023: "The Factorial for [{0}] is [{1}]"
num, 
025: Factorial.Calc(num) ); 
026: } 
027: } 
028: }
在002行,一個using Functions指明了引用Functions. }
在002行,一個using Functions指明了引用Functions.DLL這個類別.如果我們在行中鍵入以下指令,就可以看到輸出:

FunctionTest 3 5 10

輸出:


Function Client

The Digit Count for String [3] is [1] Client

The Digit Count for String [3] is [1] 是 33]/35s [Theial s [Theial [1]3] 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 forThe Factorial for [10] is [3628800]

注意:當你執行這個.EXE檔案時,它所引用的DLL檔案可以是在目前目錄,子目錄,或是CORPATH這個環境變數.CORPATH這個環境變數是在.NET環境中的類路徑,用來指引系統尋找類.說白了,就是java中的CLASSPATH,明白了吧,呵呵.

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn