Deutsch

ИИ для программиста?

30.06.25 13:32
Re: ИИ для программиста?
 
alex445 патриот
в ответ alex445 30.06.25 01:46, Последний раз изменено 30.06.25 13:54 (alex445)

Спрашиваю


C# private field and abstract lazy property for it


Отвечает


// Abstract base class
public abstract class BaseClass
{
    // Private field
    private string _lazyField;


    // Abstract property to initialize the field lazily
    public abstract string LazyProperty { get; }
}


// Derived class
public class DerivedClass : BaseClass
{
    // Implement the abstract property
    public override string LazyProperty
    {
        get
        {
            if (_lazyField == null)
            {
                _lazyField = "Initialized lazily!";
            }
            return _lazyField;
        }
    }
}


// Usage
class Program
{
    static void Main()
    {
        DerivedClass obj = new DerivedClass();
        Console.WriteLine(obj.LazyProperty); // Output: Initialized lazily!
    }
}



Key Points:
Private Field: The _lazyField is private and encapsulated within the base class.
Abstract Property: The LazyProperty is abstract in the base class, forcing derived classes to define how the field is initialized.
Lazy Initialization: The derived class ensures the field is only initialized when accessed for the first time.

Всё нормально, да?

Особенно эти key points понравились - угадал все буквы, но не смог назвать слово.

 

Перейти на