using System.ComponentModel;
using System.Numerics;
using System.Threading;
namespace CSharp
{
// 객체지향 문법을 활용한 TextRPG
class Program
{
Player player;
Monster monster;
// 여러명의 몬스터를 만드려면
// 1. 우선 변수를 여러개 만듬 -> 비효율적
//Monster monster1;
//Monster monster2;
//Monster monster3;
//Monster monster4;
// 체크 하고 싶으면 if문도 여러개 만들어야됨
// 따라서 이러한 방법은 사용할 수 없음
// 즉 자료구조가 필요함
// 배열
static void Main(string[] args)
{
// 자료구조란
// 자료에 대한 구조를 말함
// 배열
// 하나의 변수로 여러가지 데이터를 묶어서 관리가능
// 하나의 타입의 자료형으로 밖에 사용할 수 없음
int a;
int[] scores = new int[] { 10,20,30,40,50 }; // 한 번만들면 변경 안됨
// 길이가 안맞으면 에러발생
// []의 숫자 생략 가능 컴파일이 몇개인지 추론함
// new 키워드를 통해서 참조 타입인것을 알 수 있음
int[] scores2 = scores;
scores[0] = 9999; // scores2[0] = 9999이다
// 배열 문법1 //
//scores[0] = 10;
//scores[1] = 20;
//scores[2] = 30;
//scores[3] = 40;
//scores[4] = 50;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(scores[i]);
}
// 5개짜리 배열을 만들었는데 6번째 데이터를 읽는 다면
// 에러가 발생 outofrange에러 발생
// 배열의 숫자 맞추는게 어렵다고 생각된다면
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
// foreach
foreach (int score in scores)
{
Console.WriteLine(score);
}
}
}
}
new 키워드를 사용해 힙 메모리에 저장 (C# 배열은 무조건 힙에 존재)int[] array = new int[5]; // 길이가 5인 정수 배열 선언
array[0] = 10;
array[1] = 20;
array[2] = 30;
array[3] = 40;
array[4] = 50;
int[] array2 = new int[] { 10, 20, 30 };
int[] array3 = new int[5] { 10, 20, 30, 40, 50 };
int[] array4 = { 10, 20, 30 };
배열은 한번 크기를 정하면 이후 크기를 변경할 수 없습니다.
(크기를 유동적으로 관리하는 자료구조는 List<T>입니다.)
int[] scores = new int[5] { 10, 20, 30, 40, 50 };
int[] scores2 = scores; // 같은 배열 메모리를 가리킴
scores2는 새로운 배열이 아니라, 기존 scores 배열의 주소를 복사해 참조하는 변수입니다.
즉, 하나의 배열을 두 변수가 공유하는 형태입니다.
scores2[0] = 9999; // scores2에서 바꾸면 scores도 함께 변경
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
foreach (int score in scores)
{
Console.WriteLine(score);
}
foreach문은 배열 전체를 순회할 때 실수할 가능성이 적고, 가독성이 좋습니다.
for (int i = 0; i < 10; i++) // 길이 5인데 10까지 반복 시도
{
Console.WriteLine(scores[i]); // IndexOutOfRangeException 발생
}
배열의 길이를 초과하는 인덱스로 접근하면 런타임 예외인
IndexOutOfRangeException이 발생합니다.
namespace CSharp_DataStructure
{
class Player
{
// 플레이어 클래스 (아직 기능 없음)
}
class Monster
{
// 몬스터 클래스 (아직 기능 없음)
}
class Program
{
Player player; // 플레이어 객체 선언
Monster monster1; // 몬스터1 선언
Monster monster2; // 몬스터2 선언
Monster monster3; // 몬스터3 선언
static void Main(string[] args)
{
int[] scores = new int[5] { 10, 20, 30, 40, 50 };
// 힙 메모리에 길이 5짜리 정수 배열 할당 후 초기화
int[] scores2 = scores;
// scores2는 scores와 같은 배열을 가리킴 (Call by Reference)
scores2[0] = 9999;
// scores2[0]를 바꾸면 scores[0]도 같이 변경됨
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
// 전통적 for문을 이용한 순회
foreach (int score in scores)
{
Console.WriteLine(score);
}
// foreach문을 이용한 순회 (더 직관적)
// 아래 코드는 실행 시 예외 발생
// for (int i = 0; i < 10; i++)
// {
// Console.WriteLine(scores[i]); // IndexOutOfRangeException
// }
| 구분 | 배열(Array) | 리스트(List) |
|---|---|---|
| 메모리 | 연속된 공간 | 연속적일 수도, 아닐 수도 있음 |
| 크기 | 고정 | 가변 |
| 성능 | 빠름 | 비교적 느림 |
| 참조 특성 | Call by Reference | Call by Reference |
| 기능 | 단순 데이터 저장 | 다양한 메서드 제공 (Add, Remove 등) |