
簡單的 C# 程式只需要定義有 Main() 方法 (method) 的類別,但是如果要用為程式庫 (library) ,就得先定義名稱空間,名稱空間同時也是 C# 組織類別的方式。
我們在 Encrypt 之外加入 Encryptor 名稱空間的定義,另外把 Main() 拿掉,修改如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | namespace Encryptor { class Encrypt { private string cArray; public string Code { get { return cArray; } set { if (value is string && value.Length == 26) { cArray = value; } else { System.Console.WriteLine( "something worng!!" );; } } } public Encrypt() { System.Random r = new System.Random(); int a = 0; int b = 0; // 限定 a 為偶數 while (a % 2 == 0) { a = r.Next(1, 10); b = r.Next(1, 10); } System.Console.Write( "a: " + a + ", b: " + b + ", " ); int x, y, m; char c = 'a' ; int i; System.Text.StringBuilder s = new System.Text.StringBuilder(); for (i = 0; i < 26; i++) { x = c; y = x * a + b; m = y % 26; s.Append(( char ) (m + 97)); c++; } this .cArray = s.ToString(); } public string toEncode( string s) { System.Text.StringBuilder r = new System.Text.StringBuilder(); // 進行編碼轉換 char c; int i, m; for (i = 0; i < s.Length; i++) { if (s[i] >= 97 && s[i] <= 122) { c = s[i]; m = c - 97; r.Append( this .Code[m]); } else { r.Append(s[i]); } } // 回傳字串 return r.ToString(); } public string toDecode( string s) { System.Text.StringBuilder r = new System.Text.StringBuilder(); // 進行解碼的工作 int i, j; for (i = 0; i < s.Length; i++) { if (s[i] >= 97 && s[i] <= 122) { // 找出表格中對應的索引值 for (j = 0; j < 26; j++) { if (s[i] == this .Code[j]) { r.Append(( char ) (j + 97)); break ; } } } else { r.Append(s[i]); } } return r.ToString(); } } } /* 《程式語言教學誌》的範例程式 檔名:encrypt.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2012 年 10 月 */ |
這樣我們把 encrypt.cs 編譯為程式庫檔案,然後就可以在其他程式檔案中利用 using 引入 Encryptor 名稱空間了。
中英文術語對照 | |
---|---|
程式 | program |
名稱空間 | namespace |
類別 | class |
結構 | structure |
介面 | interface |
委派 | delegate |
列舉 | Enumeration |
方法 | method |
程式庫 | library |
您可以繼續參考
軟體開發
相關目錄
回 C# 入門指南
回 C# 教材
回首頁
參考資料
http://msdn.microsoft.com/zh-tw/library/w2a9a9s3(v=vs.80).aspx
http://msdn.microsoft.com/zh-tw/library/z2kcy19k%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/0d941h9d%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/aa288466%28v=vs.71%29.aspx
沒有留言:
張貼留言