Menu
Coddy logo textTech

객체 초기화자

Coddy C# 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 70개 중 8번째.

객체 초기화자는 많은 매개변수를 가진 생성자를 호출하지 않고도 객체를 생성할 때 속성 값을 설정하는 편리한 방법을 제공합니다.

생성자를 사용하는 전통적인 방식

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

Person person = new Person();
person.Name = "Alice";
person.Age = 25;
person.City = "New York";

객체 초기화 구문 사용하기

Person person = new Person
{
    Name = "Alice",
    Age = 25,
    City = "New York"
};

생성자를 사용한 객체 이니셜라이저

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
    
    public Person(string name)
    {
        Name = name;
    }
}

// 생성자는 Name을 설정하고, 이니셜라이저는 다른 속성들을 설정합니다.
Person person = new Person("Bob")
{
    Age = 30,
    City = "London"
};

중첩된 객체 이니셜라이저

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

Person person = new Person
{
    Name = "Charlie",
    Address = new Address
    {
        Street = "123 Main St",
        City = "Boston"
    }
};

초기화자를 사용하여 여러 객체 생성하기

Person person1 = new Person { Name = "Alice", Age = 25 };
Person person2 = new Person { Name = "Bob", Age = 30 };
Person person3 = new Person { Name = "Charlie", Age = 35 };

객체 이니셜라이저는 코드를 더 깔끔하고 읽기 쉽게 만듭니다. 속성은 생성자가 실행된 후에 설정됩니다. 생성자 매개변수의 유무와 관계없이 이니셜라이저를 사용할 수 있어 객체 생성이 유연하고 간결해집니다.

challenge icon

챌린지

중급

서로 다른 객체 초기화 방식을 사용하여 세 개의 Student 객체를 생성하세요:

  • student1: 기본 생성자와 객체 초기화자를 사용하여 입력값으로부터 모든 속성(Name, StudentId, Major, GPA)을 설정하세요.
  • student2: 객체 초기화자를 사용하여 Name = "Bob" 및 Major = "Engineering"만 설정하세요.
  • student3: "Charlie"를 매개변수로 하는 생성자를 사용한 후, 객체 초기화자를 사용하여 StudentId = 54321, Major = "Mathematics", GPA = 3.5를 설정하세요.

치트 시트

객체 이니셜라이저는 객체를 생성할 때 속성 값을 설정하는 편리한 방법을 제공합니다:

Person person = new Person
{
    Name = "Alice",
    Age = 25,
    City = "New York"
};

객체 이니셜라이저는 생성자와 결합될 수 있습니다:

Person person = new Person("Bob")
{
    Age = 30,
    City = "London"
};

중첩된 객체 이니셜라이저를 사용하면 중첩된 객체의 속성을 설정할 수 있습니다:

Person person = new Person
{
    Name = "Charlie",
    Address = new Address
    {
        Street = "123 Main St",
        City = "Boston"
    }
};

여러 객체를 간결하게 생성할 수 있습니다:

Person person1 = new Person { Name = "Alice", Age = 25 };
Person person2 = new Person { Name = "Bob", Age = 30 };

직접 해보기

using System;

class Program
{
    static void Main()
    {
        string name = Console.ReadLine();
        int studentId = int.Parse(Console.ReadLine());
        string major = Console.ReadLine();
        double gpa = double.Parse(Console.ReadLine());
        
        // TODO: 모든 속성에 대해 객체 초기화자를 사용하여 student1을 생성하세요
        // 기본 생성자를 사용하고 Name, StudentId, Major, GPA를 설정하세요
        
        // TODO: Name과 Major만 사용하여 객체 초기화자로 student2를 생성하세요
        // Name은 "Bob", Major는 "Engineering"이어야 합니다
        
        // TODO: 이름 매개변수가 "Charlie"인 생성자를 사용하여 student3을 생성하세요
        // 그런 다음 객체 초기화자를 사용하여 StudentId = 54321, Major = "Mathematics", GPA = 3.5로 설정하세요
        
        Console.WriteLine($"Student 1: {student1.Name} (ID: {student1.StudentId}) - {student1.Major}, GPA: {student1.GPA}");
        Console.WriteLine($"Student 2: {student2.Name} (ID: {student2.StudentId}) - {student2.Major}, GPA: {student2.GPA}");
        Console.WriteLine($"Student 3: {student3.Name} (ID: {student3.StudentId}) - {student3.Major}, GPA: {student3.GPA}");
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨