개발/공부
[유니티, C#] 일반화(Generic)
ssong_dev
2022. 6. 15. 13:52
확장메소드에 이어서 확장메소드를 제네릭하여 사용할 수 있다.
where T 로 T 범위를 지정해야 한다. 그렇지 않으면 T의 성격이 모호하여 사용할 수 없기 때문이다.
public static T DeepCopy<T>(this T value) where T : class, new()
{
T clone = new T();
return clone;
}
public static void Test<T>(this T value) where T : Component
{
Debug.Log("TEST");
}
싱글턴 패턴도 제네릭할 수 있다.
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
public static T instance = null;
private void Awake()
{
if(instance == null)
{
instance = (T)this;
}
else
{
Destroy(gameObject);
}
}
}
이런식으로 일반화 해 두면 싱글턴 패턴을 간단히 상속할 수 있다.
public class GameManager : Singleton<GameManager>
{
private void Start()
{
...
}
}
제네릭 논제네릭 차이에 대해
https://hongjuzzang.github.io/java/java_generic/
[java] Generic 알아보기
generic, 제너릭이란?
hongjuzzang.github.io