[TIL] 25.02.02 SUN

GDORI·2025년 2월 2일
0

TIL

목록 보기
178/184
post-thumbnail

어제 배운 내용 활용

25.02.01 - TIL

메서드 탐색 및 등록

진행중인 프로젝트에서 opcode에 따른 패킷 핸들러가 있는데, 하나씩 추가하기보다는 동적으로 opcode에 맞는
메서드를 자동으로 등록시키면 좋을 것 같아 위의 내용을 알아보았다. particial class 라 기본 골자는 다른분이 작성하여 초기화 부분만 작성해봤다.

using UnityEngine;
using System.Reflection;
using System.Linq;
using System;

namespace VampireSurvibal.Net
{
    public partial class PacketHandler
    {
        
        public void InitializingHandler()
        {
            // opcode와 같은 이름의 private 메서드 자동 초기화

            // private 메서드 읽기
            MethodInfo[] methods = GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
            
            // enum에 등록된 이름과 동일한 메서드만 초기화
            foreach (eOpcode opcode in Enum.GetValues(typeof(eOpcode)))
            {
                // opcode명 
                string methodName = opcode.ToString();
                
                // LINQ로 원하는 메서드 추출
                MethodInfo method = methods.FirstOrDefault(m => m.Name == methodName 
                                                               && m.ReturnType == typeof(void) 
                                                               && m.GetParameters().Length == 1 
                                                               && m.GetParameters()[0].ParameterType == typeof(Header));

                if (method != null)
                {
                    // 메서드 인포로 델리게이트 생성
                    Action<Header> action = (Action<Header>)Delegate.CreateDelegate(typeof(Action<Header>), this, method);

                    // 핸들러 등록
                    RegisterHandler(opcode, action);
                }
            }
            Debug.Log("핸들러 초기화 완료");
        }
        
        // 예시 메서드
        private void makeRoom(Header rcvHeader)
        {
            // 처리
        }

        private void joinRoom(Header rcvHeader)
        {
            // 처리
        }
    }
}
profile
하루 최소 1시간이라도 공부하자..

0개의 댓글

관련 채용 정보