Skip to content

CSharp Keyword interface

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: interface

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

Оголошує контракт типу. Підтримує члени екземпляра, реалізації за замовчуванням і static abstract члени.

Простий приклад (Example.cs)

Збережіть цей приклад окремо як Example.cs. Запускайте його незалежно від інших прикладів на сторінці.

Example.cs:

// PROJECT-EXAMPLE
ILabel item = new Item();
System.Console.WriteLine(item.Label);
interface ILabel { string Label { get; } }
class Item : ILabel { public string Label => "Ore"; }

Результат:

Ore

Синтаксис

interface IName { ... }

Приклад 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)
    {
        Entity entity = new Player("Archer");
        Console.WriteLine(entity.Describe());
        Console.WriteLine(entity.Code);
    }
}
public interface ILabel { string Label { get; } }
public abstract class Entity : ILabel
{
    private readonly string name;
    protected Entity(string name) { this.name = name; }
    protected string Name => name;
    internal int Code { get; set; } = 7;
    public virtual string Label => Name;
    public abstract string Describe();
}
public sealed class Player : Entity
{
    public Player(string name) : base(name) { }
    public override string Label => "Player: " + base.Label;
    public override string Describe() => Label;
}

Приклад 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(MathFactory.Get<Number>());
    }
}
public interface IValue<T> where T : IValue<T> { static abstract int Value { get; } }
public struct Number : IValue<Number> { public static int Value => 12; }
public static class MathFactory { public static int Get<T>() where T : IValue<T> => T.Value; }

Офіційне джерело: Microsoft Learn.

Clone this wiki locally