[C#] 확장 메서드의 이해

Yoo Hyung Joo ·2023년 10월 24일
0

확장메서드

정의
확장메서드는 원하는 클래스에 특정 함수를 추가해주는 메서드를 의미한다. 클래스의 외부에서 이미 그 확장메서드가 있는 것 처럼 추가해주는 것이다.

ex) DOTween

transform.DOLocalMoveX(1f,1f);

유니티 개발자라면 DOTween이라는 에셋을 한 번씩은 써보았을 것이다. Tween과 Easing등 여러가지 기능이 담겨있는 것인데 이 DOTween이라는 에셋을 추가하면 transform과 같은 클래스의 확장메서드가 달려 저러한 "DoLocalMoveX" 와 같은 메서드를 사용할 수 있는 것이다.

사용방법

public static void Swap(this object[] array, int index1, int index2)
{
	(array[index1], array[index2]) = (array[index2], array[index1]);
}
  1. 확장메서드를 선언해주는 클래스 자체는 static 이어야 한다.
  2. static으로 메서드를 선언해준다.
  3. 확장해줄 것을 this 키워드 를 통해서 알려준다.
    ex)
Log(this float a,float log) //float에 확장 메서드를 추가해준다. 10f.Log(200f);

사용한 예시 코드

 public static class ArrayExtensionMethod
    {
        public static object Find(this object[] array, object findItem)
        {
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].Equals(findItem))
                {
                    return array[i];
                }
            }

            return null;
        }

        public static void Swap(this object[] array, int index1, int index2)
        {
            (array[index1], array[index2]) = (array[index2], array[index1]);
        }

        public static void Add<T>(this T[] array, T item) where T : class,new()
        {
            var isSerializable = item.GetType().IsSerializable;
            var defaultObj = isSerializable ? new T() : default(T);
            
            for (int i = 0; i < array.Length; i++)
            {
                if(array[i].Equals(defaultObj))
                {
                    array[i] = item;
                    return;
                }
            }
        }
        
        public static void Add(this object[] array, object item) 
        {
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] == null)
                {
                    array[i] = item;
                    return;
                }
            }
        }
        
        public static void Clear(this object[] array)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = null;
            }
        }
    }
    

느낀점
졸업작품 프로젝트를 진행하게 되면서 이러한 확장메서드를 사용하게 되었다. 인벤토리를 사용할 때 배열을 이용하기로 했는데 이러한 과정에서 List의 장점과 같은 기능들을 직접 구현해줘야되는 수고가있었다. 하지만 이렇게 확장메서드를 구현하고 나니 배열을 사용할 때 내가 원하는 입맛대로 편하게 사용할 수 있어서 굉장히 편리했다.

profile
성장을 멈추지 않는 개발자

0개의 댓글