文章目錄
實驗一 (生成一個簡單的.NET應用程序)
學習目的:
- 掌握Visual Studio.NET創建、編譯、運行一個控制檯應用程序的方法
- 掌握使用MSIL反彙編程序來查看程序集的方法
**
1.在VS中創建控制檯應用程序
**
- 新建項目,選擇C#項目中的"控制檯應用程序",並指定保存路徑(eg:D:\C#\01)
- 將程序命名爲FirstConsoleApp,代碼如下:
using System;
// This class exists only to house the program entry point
public class MainApp
{
// Static method "Main" is application's entry point
public static void Main()
{
// get user input
Console.WriteLine("Type your name and press Enter");
string name = Console.ReadLine();
// Write text to the console
Console.WriteLine("Hello " + name);
}
- 保存全部程序,選擇“生成”菜單下“生成解決方案”,然後按CTRL+F5快捷鍵,或者單擊菜單中“調試”|“啓動”運行當前程序(必須做)
- 退出VS,運行cmd,或者單擊“Visual Studio.NET命令提示”進入命令行窗口,然後在本項目目錄“\bin\debug”下運行程序FirstConsoleApp.exe顯示結果。
2.使用記事本來創建和編譯源文件
- 打開記事本,創建一個類Hello.cs。(例如在D:/VS路徑下)
- 在記事本中編寫代碼(導入system命名空間,定義程序的入口點)
- 打開VS下的命令窗口,cd到達該項目所在文件夾下
- dir命令查看文件夾下所有文件
- 在此路徑下使用命令csc /t:exe Hello.cs生成可執行文件(exe)
- 生成exe文件後在當前路徑下輸入命令Hello.exe執行可執行文件得出結果。
3.使用MSIL反彙編程序來查看程序集
- 打開VS.NET的命令提示符窗口
- 在VS.NET命令提示符窗口鍵入: Ildasm /source
- 彈出一個窗口,點擊文件找到可執行文件,雙擊後可查看相關內容。
實驗二 (創建NET Framework組件並調用)
學習目的:
- 能夠使用C#創建組件並應用。
1.創建dll組件方式(例子)
實驗步驟:
- 打開記事本並引用system命名空間
- 創建一個新的命名空間,命名爲CompCS,CompCS將包含組件的類。
- 將文件命名爲CompCS.cs。保存
- 代碼如下:
using System;
namespace CompCS {
public class StringComponent {
private string[] StringSet;
public StringComponent() {
StringSet = new string[] {
"C# String 0",
"C# String 1",
"C# String 2",
"C# String 3"
};
}
public string GetString(int index) {
if ((index < 0) || (index >= StringSet.Length)) {
throw new IndexOutOfRangeException();
}
return StringSet[index];
}
public int Count {
get { return StringSet.Length; }
}
}
}
- 編譯源代碼,在VS.NET命令提示窗口中,通過在文件路徑下輸入命令 csc /t:library CompCS.cs 將CompCS.cs源文件生成名爲CompCS.dll的庫文件。
2.調用dll組件
- 編寫代碼來調用組件
- 將一個 C#的stringcomponent類的新實例賦值給名爲mycsstringcomp的局部變量
- 編寫代碼來向控制檯輸出如下字符串:
String from C# stringcomponet - 遍歷C#字符串組件的所有成員,並向控制檯輸出字符串
- 將文件命名爲clientcs.cs,並保存,保證該文件與CompCS.dll組件在一個目錄下
- 調用CompCS.dll的代碼如下:
using System;
using CompCS;
using CSStringComp = CompCS.StringComponent;
class MainApp
{
public static void Main()
{
CSStringComp myCSStringComp = new CSStringComp();
Console.WriteLine("String from C# StringComponent");
for (int index = 0; index < myCSStringComp.Count; index++)
{
Console.WriteLine(myCSStringComp.GetString(index));
}
}
}
- 在VS命令窗口下,並在clientcs.cs文件所在路徑下輸入以下命令:
- csc /r:CompCS.dll /out:clientcs.exe clientcs.cs生成可執行程序clientcs.exe文件(注意:dll後有空格)
- 在路徑下輸入命令clientcs.exe則可完成調用組件並執行得到結果