C# getter와 setter의 사용에 대한 설명과 적절한 예시

unity에서 기존에 만들어놓은 프로퍼티를 사용함에 있어서 프로퍼티에 대한 이해가 필요하기 때문에

그에 대한 이해를 돕기 위해서 설명과 이해를 돕기위한 예시를 gpt에 질의하여서 얻은 답변을 첨부해놓는다.

프로퍼티의 사용의 경우는 개인이 유니티 엔진에서의 프로젝트를 진행하는데 있어서는 필수적인 요소로 보여지지는 않을 수 있겠으나, 협업에 있어서는 내가 설계한 클래스 내부의 변수 자체에 대해 통제없이 접근하지 못하도록 하는데 있어서는 필수적인 요소로 생각할 수 있으므로 이에대한 이해를 높이고 더욱 익숙해지기 위한 노력을 기울여야 할 것이다.


gpt를 통한 property 의 이해

Property를 이해하는 데 도움이 될 수 있는 간단한 예시를 살펴보겠습니다. 예시로는 간단한 사용자 클래스를 가정하고, 이 클래스에 이름(Name)과 나이(Age)를 나타내는 두 가지 속성을 추가할 것입니다.

using System;

public class User
{
    // Private fields to store the actual data
    private string name;
    private int age;

    // Property for the Name field
    public string Name
    {
        get { return name; }
        set
        {
            // Additional logic can be added here before setting the value
            if (value != null && value.Length > 0)
            {
                name = value;
            }
            else
            {
                Console.WriteLine("Invalid name!");
            }
        }
    }

    // Property for the Age field
    public int Age
    {
        get { return age; }
        set
        {
            // Additional logic can be added here before setting the value
            if (value >= 0)
            {
                age = value;
            }
            else
            {
                Console.WriteLine("Invalid age!");
            }
        }
    }

    // Constructor for the User class
    public User(string name, int age)
    {
        // Use the properties to ensure data validation
        Name = name;
        Age = age;
    }

    // Method to display user information
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

class Program
{
    static void Main()
    {
        // Creating an instance of the User class
        User user = new User("John Doe", 25);

        // Accessing properties
        Console.WriteLine($"Original Name: {user.Name}");
        Console.WriteLine($"Original Age: {user.Age}");

        // Modifying properties
        user.Name = "Jane Doe";
        user.Age = 30;

        // Accessing properties after modification
        Console.WriteLine($"Modified Name: {user.Name}");
        Console.WriteLine($"Modified Age: {user.Age}");

        // Trying to set invalid values
        user.Name = "";
        user.Age = -5;

        // Displaying user information
        user.DisplayInfo();
    }
}

위의 예시에서 User 클래스는 NameAge라는 두 개의 속성을 가지고 있습니다. 각 속성에는 getset 접근자가 있어서 외부에서 이 속성들을 읽거나 쓸 수 있습니다. 또한 각 속성에는 추가적인 로직을 삽입하여 유효성 검사 등의 작업을 수행할 수 있습니다.


  Comments,     Trackbacks