// helloworld.cs
using System;
class Hello
{
static void Main()
{
Console.WriteLine("Hello, C# World!");
}
}
儲存為 helloworld.cs,命令列編譯:csc helloworld.cs,產生 helloworld.exe。
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# 開啟檔案";
fdlg.InitialDirectory = @"c:\";
fdlg.Filter = "所有檔案 (*.*)|*.*|文字檔 (*.txt)|*.txt";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName;
// 可用 fdlg.OpenFile() 取得 Stream 讀取內容
}
使用 System.Reflection 與 Activator.CreateInstance 透過 ProgID 建立 COM 物件,無需匯入型別程式庫(早期繫結)。
using System;
using System.Reflection;
using System.Threading;
class ComInteropDemo
{
static void Main()
{
Type excelType = Type.GetTypeFromProgID("Excel.Application");
if (excelType == null)
{
Console.WriteLine("未安裝 Excel");
return;
}
object excel = Activator.CreateInstance(excelType);
object[] param = new object[] { true }; // Visible = true
try
{
excelType.InvokeMember("Visible",
BindingFlags.SetProperty, null, excel, param);
Console.WriteLine("Excel 已顯示,5 秒後關閉...");
Thread.Sleep(5000);
}
catch (Exception ex)
{
Console.WriteLine("錯誤: " + ex.Message);
}
finally
{
// 釋放 COM 物件
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
}
}
}
核心類別在 System.Threading 命名空間。
using System.Threading;
Thread thread = new Thread(new ThreadStart(WriteData));
thread.Start(); // 啟動
thread.Priority = ThreadPriority.Highest; // 設定優先權
// 暫停/繼續 (舊版 API,不建議新程式使用)
if (thread.ThreadState == ThreadState.Running) thread.Suspend();
if (thread.ThreadState == ThreadState.Suspended) thread.Resume();
// 終止
if (thread.IsAlive) thread.Abort(); // 強制終止,可能造成資源洩漏
// 延遲
Thread.Sleep(1000); // 目前執行緒睡眠 1 秒
void WriteData()
{
for (int i = 0; i <= 10000; i++)
{
string str = "Secondary Thread " + i;
Console.WriteLine(str);
// UI 更新需用 Invoke/BeginInvoke 回主執行緒
}
}
Task.Run、async/await,而非手動管理 Thread。Control.Invoke (WinForms) 或 Dispatcher.Invoke (WPF)。Marshal.ReleaseComObject,並搭配 GC.Collect()、GC.WaitForPendingFinalizers() 確保釋放。System.Windows.Forms,需參考對應組件。