주어진 객체에 테스트를 진행해서, 그 결과를 반환해준다.
사용 방법
Predicate는 다른 대리자 Action, Delegate와는 다르게, 특정 시점에 호출해주는 콜백의 역할이 아닌, 객체에 대한 조건을 만들어서, 테스트할 수 있다.
- 무조건 반환이 있어야 하며, 기본 반환 형식은 boolean이다.
- 함수, 메서드, 람다를 활용하여 Predicate를 만들 수 있다.
- Predicate를 인자로 사용 가능하다.
장점
만들어진 predicate는 객체의 상태를 확인, 객체를 찾고, 정렬, 분류하는 기준으로 사용될 수 있다.
또한, 위와 같은 사용으로 반복적인 조건문의 사용을 줄여서, 코드의 재사용과 유지보수에 용이하다.
예시
using System;
using System.Collections.Generic;
using UnityEngine;
public class Test_Predicate : MonoBehaviour
{
private List<int> list = new List<int>() { 0, 1, 2, 3, 4 };
private Predicate<int> TestValueA => delegate (int a) { return a != 0; };
private Predicate<int> TestValueB = (int c) => { return c == 2; };
private Predicate<int> TestValueC;
private void Start()
{
TestValueC = ValueTest;
List<int> listA = list.FindAll(TestValueA);
foreach (int value in listA)
{
Debug.Log(value);
}
Debug.Log(TestValueA(0));
Debug.Log(TestValueA(1));
foreach(int value in list)
{
Debug.Log(TestValueB(value));
}
Debug.Log(TestValueC(0));
Debug.Log(TestValueC(1));
Debug.Log(TestValueC(2));
}
private bool ValueTest(int aValue)
{
if(aValue % 2 == 1)
{
return true;
}
return false;
}
}//실행 결과 : TestValueA에 대한 배열의 foreach 출력 결과는 0을 제외한 숫자가 출력된다, 또한 Log 2개는 각각 false, true가 출력된 것을 확인할 수 있다.
// TestValueB에 대한 실행 결과는 2는 true를 출력하고, 2를 제외한 다른 숫자들은 false를 출력하는 모습을 확인할 수 있다.
// TestValueC에 대한 실행 결과는 홀수일 때만 true를 출력하고, 나머지는 false를 출력하는 모습을 확인할 수 있다.
'유니티 > 개념 정리' 카테고리의 다른 글
| 대리자 활용 (0) | 2024.11.19 |
|---|---|
| IEnumerable과 IEnumerator (0) | 2024.11.18 |
| Static(정적) (0) | 2024.11.04 |
| Interface (0) | 2024.10.30 |
| ObjectPool (0) | 2024.10.23 |