메소드 결과를 참조로 반환

00·2024년 12월 11일

C#

목록 보기
7/149
using System; // System 네임스페이스를 사용

namespace Hello // Hello 네임스페이스 정의
{
    class Product // Product라는 이름의 클래스를 정의합니다.
    {
        public int price = 100; // public 접근 제한자를 가진 정수형 필드 price를 선언하고 100으로 초기화합니다.


        public ref int GetPrice() //  GetPrice라는 이름의 메서드를 정의합니다. ref 키워드를 사용하여 price 필드의 참조를 반환합니다.

        {
            return ref price; // price 필드의 참조 반환
        }

        public void PrintPrice() // public 메서드 PrintPrice() 정의, void 반환
        {
            Console.WriteLine($"Price : {price}"); // price 필드 값 출력
        }

        class MainApp // MainApp 클래스 정의
        {
            static void Main(string[] args) // 프로그램 진입점 Main 메서드 정의
            {
                Product carrot = new Product(); // Product 클래스의 인스턴스 carrot 생성
                ref int ref_local_price = ref carrot.GetPrice(); // ref_local_price 변수에 carrot.GetPrice()의 참조 저장
                int normal_local_price = carrot.GetPrice(); // normal_local_price 변수에 carrot.GetPrice()의 값 저장

                carrot.PrintPrice(); // carrot의 PrintPrice() 메서드 호출 (Price : 100 출력)
                Console.WriteLine($"Ref Local Price : {ref_local_price}"); // ref_local_price 값 출력 (Ref Local Price : 100 출력)
                Console.WriteLine($"Normal Local Price : {normal_local_price}"); // normal_local_price 값 출력 (Normal Local Price : 100 출력)

                ref_local_price = 200; // ref_local_price 값을 200으로 변경

                carrot.PrintPrice(); // carrot의 PrintPrice() 메서드 호출 (Price : 200 출력)
                Console.WriteLine($"Ref Local Price : {ref_local_price}"); // ref_local_price 값 출력 (Ref Local Price : 200 출력)
                Console.WriteLine($"Normal Local Price : {normal_local_price}"); // normal_local_price 값 출력 (Normal Local Price : 100 출력)
            }
        }
    }
}
Price : 100
Ref Local Price : 100
Normal Local Price : 100
Price : 200
Ref Local Price : 200
Normal Local Price : 100

코드 분석

Product 클래스는 price라는 정수형 필드와 GetPrice(), PrintPrice() 메서드를 가지고 있습니다.

GetPrice() 메서드는 ref 키워드를 사용하여 price 필드의 참조를 반환합니다.

MainApp 클래스의 Main 메서드에서는 Product 클래스의 인스턴스 carrot을 생성하고, GetPrice() 메서드를 사용하여 price 필드의 참조와 값을 각각 ref_local_price 변수와 normal_local_price 변수에 저장합니다.

ref_local_price는 price 필드의 "참조"를 저장하기 때문에,
ref_local_price 값을 변경하면 price 필드의 값도 변경됩니다.

normal_local_price는 price 필드의 값을 "복사"하여 저장하기 때문에, normal_local_price 값을 변경해도 price 필드의 값은 변경되지 않습니다.

이 코드는 ref 키워드를 사용하여 참조를 반환하는 방법과 참조를 통해 변수의 값을 변경하는 방법을 보여줍니다.

0개의 댓글