ZH TW CSharp Keyword extern - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: extern

使用手冊C# · 實用指南

聲明在C#程式碼之外實現的成員;典型的透過DllImport進行本機互通。 extern alias 指定外部組件別名。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
class NativeMethods
{
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    public static extern uint GetCurrentProcessId();
}

僅宣告:此程式碼編譯為程式庫;要執行,請從 Main 呼叫。

句法

[DllImport(...)] public static extern ReturnType Method(...);

這兩個本機範例適用於 Windows。函式庫名稱、ABI 和功能可用性取決於平台;編譯本身不會檢查它們是否存在。

例1:基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetCurrentProcessId());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static extern uint GetCurrentProcessId(); }

例2:另一種實用形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetTickCount64());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static extern ulong GetTickCount64(); }

官方來源:Microsoft學習。