[Unity] 나는 Boxing이 뭔지 알고 있을까
![[Unity] 나는 Boxing이 뭔지 알고 있을까](/_next/image?url=https%3A%2F%2Fdata.develog.develrocket.com%2Fupload%2Fdevelog%2Fgmumdev%2F1790954185360-cyx8ex%2F_____.png&w=3840&q=75)
Boxing is the process of converting a value type to the type
objector to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System.Object instance and stores it on the managed heap.박싱은 값 타입을
object타입 또는 그 값 타입이 구현한 인터페이스 타입으로 변환하는 과정이다. CLR은 값을 System.Object 인스턴스로 감싸 managed heap에 저장한다
- Microsoft learn <링크>
using UnityEngine;
[System.Serializable]
public struct EnemyData
{
public int id;
public int biome;
public EnemyData(int id, int biome)
{
this.id = id;
this.biome = biome;
}
}
public class Enemy : MonoBehaviour
{
[SerializeField] private EnemyData data;
}
using UnityEngine;
using System.Collections.Generic;
[System.Serializable]
public struct EnemyData
{
public int id;
public int biome;
public EnemyData(int id, int biome)
{
this.id = id;
this.biome = biome;
}
}
public class EnemyManager : MonoBehaviour
{
private readonly Dictionary<EnemyData, int> enemies = new(); // 뭔가 들어있다고 가정
public bool IsExist(int id, int biome)
{
return enemies.TryGetValue(new EnemyData(id, biome), out var cnt) && cnt > 0;
}
}
public struct EnemyData : IData { /* ... */ }
public static void SomeMethod(IData d) // SomeMethod(new EnemyData(...))
{
//...
}
public struct EnemyData : IData { /* ... */ }
public static void SomeMethod<T>(T data) where T : IData // SomeMethod(new EnemyData(...))
{
data.SomeInterfaceMethod();
}
private IEnumerator FadeOut(float duration)
{
float elapsed = 0f;
while (elapsed < duration)
{
elapsed += Time.deltaTime;
//...
yield return null;
}
gameObject.SetActive(false);
}
# | 상황 | 박싱 | 힙 할당 | 할당되는 것 |
|---|---|---|---|---|
1 | 클래스의 필드인 구조체 | X | X (추가 할당 없음) | 없음. |
2 |
| O | O | 박스 (조회마다) |
3 | 인터페이스 타입 매개변수로 전달 | O | O | 박스 (호출마다) |
4 | 제네릭 제약 조건 매개변수로 전달 | X | X | 없음 |
5 |
| O | O | 박스 (호출마다) |
6 | 람다의 값 타입 캡처 | X | O | DisplayClass 인스턴스, delegate 인스턴스 |
7 | 코루틴 안의 값 타입 지역 변수 | X | O | 상태 머신 인스턴스 ( |
새 글이 올라오면 Develog 알림으로 알려드려요
댓글을 작성하려면 로그인이 필요합니다.
아직 댓글이 없습니다. 첫 번째 댓글을 작성해보세요.
ㅇㅇ
![[Unity] 제네릭과 가변성(variance)](https://data.develog.develrocket.com/upload/develog/gmumdev/1791297148427-udtfz5/_____.png)
제네릭과 가변성
![[Unity] IEnumerator 개요](https://data.develog.develrocket.com/upload/develog/gmumdev/1791297506756-dx8ros/_____.png)
코루틴에이저포에버
![[Unity] 제네릭과 가변성(variance)](https://data.develog.develrocket.com/upload/develog/gmumdev/1791297148427-udtfz5/_____.png)
![[Unity] IEnumerator 개요](https://data.develog.develrocket.com/upload/develog/gmumdev/1791297506756-dx8ros/_____.png)