Unity3D/C#

C# 강좌 Day-12 (method, ref, out)

일등하이 2021. 8. 15. 15:47
반응형

메서드

어떤 작업을 수행하기 위한 명령문의 집합 

재사용 목적 

<그림 1-1>

 

메서드의 정의 > 메서드 구현 > 메서드 호출 

 

 

다음과 같이 클래스 내부에 정의한다 

C#에서의 메서드명은 보통 대문자로 시작한다 

반환 값이 없을 경우 void 를 사용한다 

반환 값이 있을경우 return문과 함께 반환값을 적어준다 

class 클래스명
{
    ...
    ...
    <접근제한자> <반환타입> 메서드이름()
    {
        //실행문
    }
    ...
    ...
}

 

PrintSayHello()라는 메서드를 정의하고 구현해보자 

기능: 호출시 Hello 라는 문자열을 출력한다 

using System;

class Program
{
    static void Main(string[] args)
    {
        //호출
        PrintSayHello();
    }

    //정의 
    static void PrintSayHello()
    {
        Console.WriteLine("Hello"); //구현 
    }
}

 

주의 :  static 메서드에서 다른 메서드를 호출 할때 다른 메서드는 static 키워드를 붙여야 한다 

 

메서드를 언제든 호출 하게 되면 해당 기능이 동작 한다 

using System;

class Program
{
    static void Main(string[] args)
    {
        //호출
        PrintSayHello();
        PrintSayHello();
        PrintSayHello();
        PrintSayHello();
        PrintSayHello();
    }

    //정의 
    static void PrintSayHello()
    {
        Console.WriteLine("Hello"); //구현 
    }
}

 

 

매개변수 

메서드 실행시 인자 값을 건네줄수 있다 

메서드 내부에서는 이 인자를 매개변수라 부르고 밖에서는 인자 또는 인수라 부른다 

class 클래스명
{
    ...
    ...
    <접근제한자> <반환타입> 메서드이름(매개변수타입 변수명)
    {
        //실행문
    }
    ...
    ...
}

위에 그림 1-1에서 밀가루는 인자에 해당한다 

이러한 인자는 ,(콤마)를 찍고 여러개를 설정 할수도 있다.

빵만드는 기능을 하는 메서드를 정의하고 구현해본다 

 

메서드명 : BakeBread

인자값 : 밀가루 

기능: 밀가루를 반죽해서 오븐에 넣고 빵을 만든다

using System;

class Program
{
    static void Main(string[] args)
    {
        //호출
        BakeBread("밀가루");
    }

    //정의 
    static void BakeBread(string ingredient) {
        Console.WriteLine("{0}(을)를 반죽합니다.", ingredient);
        Console.WriteLine("오븐에 굽습니다.");
        Console.WriteLine("빵이 만들어졌습니다.");
    }
}

 

 

 

반환값과 반환타입 

 

메서드 내부에서 반환값은 호출자에게 전달되는 값이다

반환 값이 있을 경우 return 문과 함께 사용한다 

class 클래스명
{
    ...
    ...
    <접근제한자> <반환타입> 메서드이름()
    {
        //실행문
        return <반환값>
    }
    ...
    ...
}

 

 

위에서 만든 BakeBread에 문자열 "잘 구워진  빵"을 반환 하도록 변경 해보자 

using System;

class Program
{
    static void Main(string[] args)
    {
        //호출
        BakeBread("밀가루");
    }

    //정의 
    static string BakeBread(string ingredient) {
        Console.WriteLine("{0}(을)를 반죽합니다.", ingredient);
        Console.WriteLine("오븐에 굽습니다.");
        Console.WriteLine("빵이 만들어졌습니다.");
        return "잘 구워진 빵";
    }
}

 

호출이 완료 되고 호출자에게 반환되는 값은 변수에 할당 가능하다 

//호출
string bread = BakeBread("밀가루");

 

 

연습해보기 

 

 

매개변수 두개를 더한 값을 반환 하는 Sum메서드를 작성 하세요 

using System;

class Program
{
    static void Main(string[] args)
    {
        int result = Sum(1, 2);
        Console.WriteLine(result);
    }

    static private int Sum(int a, int b)
    {
        int sum = a + b;
        return sum;
    }
}

 

 

동쪽으로 이동할수 있는 메서드 와 아이템 착용하는 메서드를 작성하세요

using System;

class Program
{
    static void Main(string[] args)
    {
        MoveEast();
        EquipItem();
    }

    //동쪽으로 이동 
    static private void MoveEast()
    {
        Console.WriteLine("동쪽으로 이동했습니다.");
    }

    //아이템 착용 
    static private void EquipItem()
    {
        Console.WriteLine("아이템을 착용했습니다.");
    }
}

 

 

 

이번에는 동서남북으로 이동 가능한 각 메서드와 아이템 착용메서드를 작성해봅니다 

using System;

class Program
{
    static void Main(string[] args)
    {
        MoveEast();
        MoveEast();
        MoveNorth();
        MoveNorth();
        MoveWest();
        MoveSouth();
        EquipItem();
    }

    //동쪽으로 이동 
    static private void MoveEast()
    {
        Console.WriteLine("동쪽으로 이동했습니다.");
    }

    //서쪽으로 이동 
    static private void MoveWest()
    {
        Console.WriteLine("서쪽으로 이동했습니다.");
    }

    //남쪽으로 이동 
    static private void MoveSouth()
    {
        Console.WriteLine("남쪽으로 이동했습니다.");
    }

    //북쪽으로 이동 
    static private void MoveNorth()
    {
        Console.WriteLine("북쪽으로 이동했습니다.");
    }

    //아이템 착용 
    static private void EquipItem()
    {
        Console.WriteLine("아이템을 착용했습니다.");
    }
}

 

 

 

매개변수로 동서남북중 하나의 문자열을 전달받아 이동하는 메서드를 작성하세요 

using System;

class Program
{
    static void Main(string[] args)
    {
        Move("동");
    }

    static private void Move(string direction)
    {
        if (direction == "동")
        {
            Console.WriteLine("{0}쪽으로 이동했습니다.", direction);
        }
        else if (direction == "서")
        {
            Console.WriteLine("{0}쪽으로 이동했습니다.", direction);
        }
        else if (direction == "남")
        {
            Console.WriteLine("{0}쪽으로 이동했습니다.", direction);
        }
        else if (direction == "북")
        {
            Console.WriteLine("{0}쪽으로 이동했습니다.", direction);
        }
        else
        {
            Console.WriteLine("{0}쪽으로는 이동할수 없습니다.", direction);
        }

    }
}

 

 

 

도끼를 착용하고 해제하는 메서드를 각각 작성하세요 

using System;

class Program
{
    static void Main(string[] args)
    {
        EquipAxe();
        UnEquipAxe();
    }

    //도끼를 착용
    static private void EquipAxe()
    {
        Console.WriteLine("도끼를 착용했습니다.");
    }

    //도끼를 무장해제 
    static private void UnEquipAxe()
    {
        Console.WriteLine("도끼를 무장해제했습니다.");
    }
}

 

 

 

ref키워드 

ref 키워드는 값이 참조로 전달됨을 나타낸다 

변수를 전달하기 전에 초기화해야 합니다. 

using System;

class Program
{
    static void Main(string[] args)
    {
        int x = 10;

        PassByValue(x);
        Console.WriteLine(x);   //10

        PassByReference(ref x);
        Console.WriteLine(x);   //13
    }

    public static void PassByValue(int a)
    {
        a += 3;
    }

    public static void PassByReference(ref int a)
    {
        a += 3;
    }
}

 

 

out키워드 

out 키워드를 사용하면 참조를 통해 인수를 전달할  있다 

out 매개 변수를 사용하려면 메서드 정의와 호출 메서드가 모두 명시적으로 out 키워드를 사용해야 한다 

using System;

class Program
{
    static void Main(string[] args)
    {
        //숫자 형식의 문자열 값 -> int (정수) 형식변환 
        string str = "홍";

        int num2;
        bool isSuccess = int.TryParse(str, out num2);
        Console.WriteLine(isSuccess);
        Console.WriteLine(num2);
    }
}

 

 

https://www.tutlane.com/tutorial/csharp/csharp-pass-by-value-with-examples

https://www.geeksforgeeks.org/c-sharp-method-parameters/

https://docs.microsoft.com/ko-kr/dotnet/csharp/methods

https://www.tutorialsteacher.com/csharp/csharp-switch

https://www.w3schools.com/cs/cs_methods.php

반응형