728x90
반응형
개발하면서 평소 궁금하던 것들을 일기장 형식으로 작성한 것입니다.
참고용으로 봐주시고 피드백이 있다면 언제든지 댓글로 부탁드리겠습니다^^
편의상 본문은 평어로 서술합니다 😇
1. Func
👣 미리 C# 내에서 선언이 되어 있는 델리게이트로,
리턴 타입이 존재하는 함수만을 등록할 수 있는 제네릭 델리게이트!
(1)
static FindUnit(Func<Unit, bool> unitType) { foreach(Unit u in unitList) { if(unitType(u)) return u; } return null; } static List<Unit> unitList = new List<Unit>(); static void Main(string[] args) { unitList.Add(new Unit() { UnitType = UnitType.Marine, ArmyType = ArmyType.Ground }); unitList.Add(new Unit() { UnitType = UnitType.Dropship, ArmyType = ArmyType.Sky }); Func<Unit, bool> unitType = (Unit i) => { return i.UnitType == UnitType.Marine; }; Unit unit = FindUnit(unitType); }
public static string AddFunc(int a, int b) { return (a + b).ToString(); } static void Main(string[] args) { Func<int, int, string> funcDelegate = AddFunc; // '<입력변수, 입력변수, 반환변수>' Console.WriteLine(funcDelegate(10, 20)); // '30' }
👣 미리 C# 내에서 선언이 되어 있는 델리게이트로,
2. Action
리턴 타입이 없는 함수만을 등록할 수 있는 제네릭 델리게이트!
(1)
• 액션(이벤트)에 액션(이벤트)를 더하는 것도 가능!public static void BindEvent(GameObject go, Action<PointerEventData> action, Define.UIEvent type = Define.UIEvent.Click) { UI_EventHandler evt = Util.GetOrAddComponent<UI_EventHandler>(go); switch (type) { case Define.UIEvent.Click: evt.OnClickHandler -= action; // 없다면 무시된다! evt.OnClickHandler += action; break; case Define.UIEvent.Drag: evt.OnDragHandler -= action; // 없다면 무시된다! evt.OnDragHandler += action; break; } }
• 만약 이벤트에 해당 함수가 없는데도 빼려하는건 에러 나지 않는다. 무시될뿐!
◦ OnClickHandler 에 action 이 없더라도 빼려할 때 에러 나지 않는다! 그냥 무시!
◦ 만약 action이 OnClickHandler에 이미 등록되어 있다면 제거된다!
(2)
public static void PrintAddFunc(int a, int b) { Console.WriteLine((a + b).ToString()); } public static void PrintSubFunc(int a, int b) { Console.WriteLine((a - b).ToString()); } public static void PrintFunc(Action<int, int> Func, int a, int b) { Func(a, b); } static void Main(string[] args) { PrintFunc(PrintAddFunc, 100, 200); // '300' PrintFunc(PrintSubFunc, 200, 200); // '0' }
반응형
'[언어] > C#' 카테고리의 다른 글
[C#] 5-11 Reflection (0) | 2022.12.13 |
---|---|
[C#] 5-10 Exception (예외 처리) (0) | 2022.12.08 |
[C#] 5-8 람다식 (0) | 2022.12.07 |
[C#] 5-7 Event(이벤트) (0) | 2022.12.05 |
[C#]5-6 Delegate(대리자)-2 (0) | 2022.12.03 |