在 C# 中直接實例化 SystemTime 時,編譯器報錯:
錯誤 CS0246:未能找到類型或命名空間名稱「SystemTime」(是否缺少 using 指令或程序集引用?)
代碼示例:
SystemTime my = new SystemTime(); // 編譯失敗
SYSTEMTIME 並非 .NET Framework 基礎類庫(BCL)中的托管類型,而是 Windows API(Win32 API)定義的結構體,位於 kernel32.dll 中。C# 無法直接 new 它,必須通過 P/Invoke(平台調用) 進行互操作。
using System.Runtime.InteropServices;[StructLayout(LayoutKind.Sequential)] 標記,確保內存佈局與 Win32 API 一致。[DllImport("kernel32.dll")] 導入 GetSystemTime 或 GetLocalTime。using System;
using System.Runtime.InteropServices;
public class Win32TimeDemo
{
// 1. 定義 SYSTEMTIME 結構體
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
// 2. 導入 Win32 API
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void GetSystemTime(out SYSTEMTIME lpSystemTime);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void GetLocalTime(out SYSTEMTIME lpSystemTime);
public static void Main()
{
// 3. 調用獲取時間
GetSystemTime(out SYSTEMTIME utcTime);
GetLocalTime(out SYSTEMTIME localTime);
Console.WriteLine($"UTC時間: {utcTime.wYear}-{utcTime.wMonth:D2}-{utcTime.wDay:D2} {utcTime.wHour:D2}:{utcTime.wMinute:D2}:{utcTime.wSecond:D2}");
Console.WriteLine($"本地時間: {localTime.wYear}-{localTime.wMonth:D2}-{localTime.wDay:D2} {localTime.wHour:D2}:{localTime.wMinute:D2}:{localTime.wSecond:D2}");
}
}
DateTime.Now 更接近硬件時鐘,適合高精度場景。GetSystemTime 返回 UTC,GetLocalTime 返回本地時間,按需選擇。DateTime / DateTimeOffset,僅在需要調用底層 API 時使用 P/Invoke。掌握 P/Invoke 基礎,能讓 C# 開發者突破托管邊界,靈活調用 Windows 核心功能。