본문 바로가기

[언어]/C#

[C#] extension 확장 메서드

728x90
반응형

개발하면서 평소 궁금하던 것들을 일기장 형식으로 작성한 것입니다.
참고용으로 봐주시고 피드백이 있다면 언제든지 댓글로 부탁드리겠습니다^^
편의상 본문은 평어로 서술합니다 😇

 

1. Extension
👣 특수한 종류의 static 메서드인데, 마치 다른 클래스의 메서드인 것처럼 호출해서 사용 가능!

public static class Extension
{
    public static T GetOrAddComponent<T>(this GameObject obj) where T : UnityEngine.Component
    {
        return Util.GetOrAddComponent<T>(obj);
    }
    
    public static void BindEvent(this Gameobject obj, Action<PointerEventData> action, Define.UIEvent type = Define.UIEvent.Click)
    {
        return UI_Base.BindEvent(obj, action, type);
    }
}​

Extension 클래스가 "static" class Extension인 것과 함수들이 static인 것에 주목! -> 확장 메서드
    ◦ 클래스는 Monobehaviour 상속❌
GetOrAddComponent
    ◦ 매개 변수가 없는 함수!
    ◦ GameObject 파라미터에서 호출할 수 있게 되었다.
      마치 GameObject의 메서드인 것처럼 사용할 수 있게됨!
        - this.GameObject obj
• BindEvent
    ◦ 매개 변수가 action, Define 2개인 함수!
    ◦ GameObject 파라미터에서 호출할 수 있게 되었다. 마치 GameObject의 메서드인 것처럼 사용할 수 있게 됨!

GetButton((int)Buttons.PointButton).gameObject.BindEvent(OnButtonClicked);

- 바로 GetButton 함수로부터 리턴받은 버튼 오브젝트에서 바로 BindEvent(OnButtonClicked) 이렇게 함수를 호출할 수 있게 되었다. 마치 GameObject에 원래 있던 메서드를 호출하는 것처럼 호출할 수 있게 된 것이다.


namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}

- 확장메서드 WordCount는 마치 String의 메서드인 것처럼 사용할 수 있게 된다! 매개 변수는 없는 함수다.

using ExtensionMethods;

string s = "Hello Extension Methods";
int i = s.WordCount();

- string 인스턴스에서 바로 호출할 수 있게 되었다! C#의 특별한 문법!

반응형

'[언어] > C#' 카테고리의 다른 글

[C#] Convert, Parse, TryParse  (0) 2023.01.03
[C#] IEnumerator : 열거자  (0) 2022.12.22
[C#] 5-12 Nullable  (0) 2022.12.19
[C#] 5-11 Reflection  (0) 2022.12.13
[C#] 5-10 Exception (예외 처리)  (0) 2022.12.08