C#(19)
-
[C#] 필드와 지역 변수의 구별
하나의 클래스 안에는 같은 이름의 필드와 지역 변수가 존재할 수 있다. using System; Class Scope { int zoom = 1; //필드 void print() { int zoom = 2; //지역 변수 ... } Console.WriteLine(zoom + "," + this.zoom); } 필드로 int zoom = 1;을 선언하였고, print() 메소드 안에 지역 변수로 int zoom = 2;를 선언하였다. Console.WriteLine(zoom + "," + this.zoom); 에서 앞의 zoom은 지역 변수 zoom을, 뒤의 this.zoom은 필드 zoom을 의미한다.
2023.10.25 -
[C#] 클래스의 소유와 참조 / 역참조와 상호 참조 / 자기 참조
소유와 참조 public class Test : MonoBehaviour { public class Father { public Child child; public int x; } public class Child { public int y; } void Start() { Father f = new Father(); Child c = new Child(); f.child = c; f.child.y = 20; c.y = 10; print(f.child.y); } } 위 코드의 클래스는 Father와 Child 두 개이다. Father 클래스는 Child 클래스의 인스턴스 child와 int x를 가지며, Child 클래스는 int y를 가진다. 변수 f와 c로 각각 해당 클래스의 메모리를 선언하였고 f.c..
2023.08.10 -
[C#] 배열, 리스트와 유니티 예제
배열은 클래스이며, 레퍼런스로 동작하기 때문에 선언만 해서는 안되고 new를 이용해 메모리를 만들어야 한다. int[] nums = new int[5]; string[] strs = new string[3]; nums, strs는 레퍼런스 변수이다. 배열 선언 int[] nums = new int[5]; nums[0] = 1; nums[1] = 2; int[] nums = new int[]{1,2,3,4,5}; int[] nums = new int[5]{1,2,3,4,5}; int[] nums = {1,2,3,4,5}; 배열의 실제 데이터는 힙 메모리 영역에 생긴다. nums 레퍼런스 변수는 스택 메모리 영역에 생긴다. 배열 접근 print(nums[0]); for(int i=0; i
2023.08.10 -
[C#] 클래스(Class) / 구조체와 클래스의 차이 / 스택 메모리와 힙 메모리 / 상속(inheritance)
구조체와 클래스는 비슷하지만 메모리 구조가 다르다. 클래스는 객체를 관리하기 위해 사용된다. 레퍼런스 변수가 있으며 실제 데이터는 레퍼런스가 가리키는 형식이다. 클래스의 실제 데이터는 힙 영역에 있다. (**함수 안의 값 형식 메모리는 스택에 존재 / 함수 밖의 값 형식 메모리는 힙에 존재) public class TestScript : MonoBehaviour { public class ClassPos { public int x; public int y; public int z; public void Show() { print(x + " " + y + " " + z); } void Start() { ClassPos cPos; cPos.x = 1; cPos.Show(); } } } 구조체와 다르게 위와 ..
2023.08.09 -
[C#] 구조체(Struct)와 생성자, this 키워드
구조체는 클래스와 마찬가지로 변수와 함수로 이루어져 있다. 데이터 중심 기반 구조체 (C 언어) public class TestScript : MonoBehaviour { public struct StructPos { public int x; public int y; public int z; } // Start is called before the first frame update void Start() { StructPos pos; pos.x = 10; pos.y = 20; pos.z = 30; print("x : " + pos.x + " y : " + pos.y + " z : " + pos.z); } } 객체 기반 구조체 (C# 언어) -내용은 모르는 채로 함수만 쓸 수 있는 경우 public cla..
2023.08.08 -
[C#] 함수의 오버로딩(Overloading)
오버로딩(Overloading) - 같은 함수 이름으로 데이터 형에 따라 다른 동작을 하게 만드는 방법 (정수형 입력 값은 정수형 출력, 실수형 출력 값은 실수형 출력) int Add(int a, int b) { return a + b; } float Add(float a, float b) { return a + b; } int와 float형 두 함수는 각각 다음과 같이 사용할 수 있다. int number1 = Add(3, 5); float number2 = Add(1.3f, 4.0f); iRandom = Random.Range(1, 10); fRandom = Random.Range(1.0f, 10.0f); 함수 오버로딩에 의하여 Random.Range 함수는 정수 값을 입력하면 정수 출력값이 나오고,..
2023.08.07