Unity 기초_2 (new, var, 컬렉션, list)

김펭귄·2025년 1월 9일

Unity 기초

목록 보기
4/9

new

List<int> intList = new List<int> intList;
string[] name = new string[3];

  • 이렇듯 new는 Heap메모리에 객체나 배열을 할당 및 초기화하고 그 주소를 반환한다
  • 그래서 처음 선언되는 intList나 name은 이 할당된 메모리 주소값을 반환받아 사용하게 된다.

Var

  • 암시적 형식 지역 변수
  • 지역 변수를 선언할 때 컴파일러가 초기화 식에서 변수의 형식을 유추
  • 선언 시 초기화도 함께, 지역변수로만
  • 초기화 후엔 자료형이 고정되며 자료형을 바꿀 수 없음
var greeting = "Hello";
Console.WriteLine(greeting.GetType());  // output: System.String

var a = 32;
Console.WriteLine(a.GetType());  // output: System.Int32

var a = 32L;
Console.WriteLine(a.GetType());  // output: System.Int64 // 정수L로 long형

var xs = new List<double>();
Console.WriteLine(xs.GetType());  // output: System.Collections.Generic.List`1[System.Double]

컬렉션 클래스

  • C#에서 지원하는 자료구조 클래스
  • ArrayList, Queue, Stack, Hashtable 등
  • object 형식으로 데이터를 관리하므로, Boxing, Unboxing 발생
  • 성능저하로 잘 사용하지 않음

제네릭 컬렉션(General Collection) 클래스

  • 특정 자료형으로만 사용하여 성능 좋음
  • List, Dictionary , Queue, Stack 등
  • using System.Collections.Generic;으로 선언해주어 사용

List

  • Microsoft Developer Network (MSDN) documentation에서는 list에 대해 다음과 같이 정의하고 있다

[It] represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

  • 배열처럼 index로 접근이 가능하며 검색, 정렬, 수정등의 기능을 제공하는 그룹형 배열이다.

List 선언

  List<T> items = new List<T>();	// 리스트 선언
  List<int> numbers = new List<int>() { 1, 2, 3 };	// 선언 및 초기화

Strongly Typed

  • 리스트를 정의할 때 특정 자료형으로만 사용할 수 있다
  • 컴파일러는 다른 자료형을 list에 사용하지 못하도록 해줌
List<string> languages = new List<string>(); // 문자열 자료형 list 선언
languages.Add("C#");	// list는 add기능 이용가능
languages.Add("Kotlin");
languages.Add(10); // 문자열이 아닌 다른 자료형이므로 compilation error!

Not Strongly Typed

  • ArrayList를 이용하면 자료형에 구애받지 않고 자유롭게 사용 가능
ArrayList items = new ArrayList();
items.Add(10);
items.Add(true);
items.Add("this wasn't supposed to be here!");
  • 단점
    • 원치 않는 자료형도 받을 수 있다
    • 성능 저하

요소 추가

  • Add
var n = new List<int>();
n.Add(15);
n.Add(30);
n.Add(42);

n이라는 정수형 list를 먼저 선언해주고, 3개의 정수값을 넣어주는 기본적인 방법


  • Insert
    n.Insert(index, item);

    삽입할 위치 값인 index와 넣을 값인 item을 통해 넣어줄 수 있다.


순회

  • for문
for (int i = 0; i < n.Count; i++)
{
	Debug.Log($"{i + 1}번째 : {n[i]}");
}

Count를 통해 list의 길이를 구할 수 있다.


  • foreach
foreach(var x in n)
{
	Debug.Log(x);
}

정렬

myList.Sort() : 오름차순으로 정렬
myList.Reverse() : 내림차순으로 정렬


Contain

n.Contains(item)
list에 item값이 있는지 확인하는 함수. True or False를 반환


Indexof

n.Indexof(item)
list의 item이 어느 위치에 있는지 반환. 없다면 -1


데이터 삭제

  • Remove
    n.Remove(item)
    첫 번째 item 값을 지움

  • RemoveAll
    n.RemoveAll(Predicate<T> match)
    리스트에서 특정 조건을 만족시키는 모든 값들을 제거

  • RemoveAt
    n.RemoveAt(index)
    리스트의 특정 위치에 있는 값 제거

  • RemoveRange
    n.RemoveRange(index, count)
    리스트에서 index 위치로부터 count개수의 값 제거

  • Clear
    n.Clear()
    리스트의 모든 요소를 제거


List 메모리 반환

  • C#은 이전에 설명했듯이 개발자가 직접 메모리를 반환하지 않음
  • 대신에 garbage collector가 더 이상 객체가 참조되지 않을 경우 자동으로 회수
  • 그러므로 선언 시 반환받았던 메모리 주소를 더 이상 참조하지 않으면 GC가 자동으로 반환해준다
List<char> alphabet = new List<char>();
...
alphabet = null;	// List를 더 이상 참조하지 않음

Reference

profile
반갑습니다

0개의 댓글