Skip to content

CSharp Keyword extern

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: extern

Довідник C# · Практичне керівництво

Оголошує член, реалізований поза C#-кодом; типово для native interop через DllImport. extern alias задає зовнішній assembly-псевдонім.

Простий приклад (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(...);

Ці два native приклади призначені для 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 Learn.

Clone this wiki locally