Skip to content

RU CSharp Keyword new

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: new

Справочник C# · Практическое руководство

Создает объект; как модификатор явно скрывает унаследованный член; как generic-ограничение требует открытый конструктор без параметров.

Простой пример (Example.cs)

Сохраните этот пример отдельно как Example.cs. Запускайте его независимо от остальных примеров страницы.

Example.cs:

// PROJECT-EXAMPLE
var child = new Child();
System.Console.WriteLine(child.Label);
System.Console.WriteLine(((Parent)child).Label);
class Parent { public string Label => "Parent"; }
class Child : Parent { public new string Label => "Child"; }

Результат:

Child
Parent

Синтаксис

new Type(...) / public new Member / where T : new()

Приклад 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)
    {
        NamedCounter value = new();
        Console.WriteLine(value.Describe());
        Counter parent = value;
        Console.WriteLine(parent.Describe());
    }
}
public interface ICounter { int Count { get; } }
public class Counter : ICounter
{
    private int count;
    public Counter() : this(1) { }
    public Counter(int count) { this.count = count; }
    public int Count => count;
    protected internal virtual string Format() => count.ToString();
    public string Describe() => Format();
}
public sealed class NamedCounter : Counter
{
    public NamedCounter() : base(4) { }
    public new string Describe() => "Named: " + base.Describe();
    protected internal override string Format() => "Count=" + Count;
}

Официальный источник: Microsoft Learn.

Clone this wiki locally