My 命名空間是 VB.NET 獨有的生產力功能,提供常用 .NET 類別的簡化進入點。C# 專案透過參考 Microsoft.VisualBasic.dll 即可使用相同功能。本文展示音訊播放、系統音效、網路連線測試等實務範例。
Microsoft.VisualBasicusing Microsoft.VisualBasic.Devices;Computer 類別整合音訊、時鐘、檔案系統、資訊、鍵盤、滑鼠、網路、登錄、螢幕等功能。
Computer myComputer = new Computer();
// 標準 C# 寫法
var player = new SoundPlayer(@"C:\Beep.wav");
player.Play();
// My 寫法:更直觀
myComputer.Audio.Play(@"C:\Beep.wav");
// 標準寫法
SystemSounds.Asterisk.Play();
// My 寫法
myComputer.Audio.PlaySystemSound(System.Media.SystemSounds.Asterisk);
// 標準寫法:需使用 Ping 類別、處理例外
var ping = new Ping();
var reply = ping.Send("www.microsoft.com");
bool reachable = reply.Status == IPStatus.Success;
// My 寫法:一行語意化程式碼
if (myComputer.Network.IsAvailable)
{
if (myComputer.Network.Ping("www.microsoft.com"))
{
MessageBox.Show("微軟網站可連線");
}
}
// 檔案系統操作
myComputer.FileSystem.CopyDirectory(@"C:\Source", @"C:\Dest");
myComputer.FileSystem.DeleteFile(@"C:\Temp\test.txt");
string content = myComputer.FileSystem.ReadAllText(@"C:\Config.ini");
// 登錄存取
myComputer.Registry.SetValue(@"HKEY_CURRENT_USER\MyApp", "Setting", "Value");
string val = myComputer.Registry.GetValue(@"HKEY_CURRENT_USER\MyApp", "Setting", "Default");
// 螢幕資訊
int width = myComputer.Screen.Bounds.Width;
int height = myComputer.Screen.Bounds.Height;
// 鍵盤/滑鼠狀態
bool ctrlPressed = myComputer.Keyboard.CtrlKeyDown;
Point mousePos = myComputer.Mouse.Position;
| 功能 | 標準 C# | My 命名空間 |
|---|---|---|
| 播放 WAV | new SoundPlayer(path).Play() | computer.Audio.Play(path) |
| 系統音效 | SystemSounds.Asterisk.Play() | computer.Audio.PlaySystemSound(...) |
| Ping 網站 | new Ping().Send(host).Status == Success | computer.Network.Ping(host) |
| 複製目錄 | Directory.Copy(...) (需遞迴自寫) | computer.FileSystem.CopyDirectory(...) |
| 讀取文字檔 | File.ReadAllText(path) | computer.FileSystem.ReadAllText(path) |
| 寫入登錄 | Registry.SetValue(...) | computer.Registry.SetValue(...) |
| 優點 | 缺點 |
|---|---|
| API 發現容易:IntelliSense 直接列出功能分類 | 額外相依 Microsoft.VisualBasic.dll |
| 語意化方法名:Audio.Play、Network.Ping 直觀易記 | 非 C# 原生,團隊可能不熟悉 |
| 封裝常見樣板碼:複製目錄、Ping 等 | 功能有限,複雜場景仍需原生 API |
| 快速原型開發、腳本式程式碼 | 跨平台專案 (.NET Core/.NET 5+) 需額外套件 |
// NuGet 安裝
dotnet add package Microsoft.VisualBasic
// 程式碼相同
using Microsoft.VisualBasic.Devices;
var computer = new Computer();
computer.Audio.Play("test.wav");
注意:Microsoft.VisualBasic.Devices.Computer 在 .NET Core 為跨平台實作,部分功能 (如登錄、系統音效) 僅限 Windows。
My 命名空間為 C# 開發者提供 VB 風格的便利 API 進入點,適合快速開發、原型驗證、腳本自動化等場景。核心價值在於API 發現性與語意化命名,降低查閱文件成本。正式專案建議視團隊熟悉度與相依性策略決定是否採用。