2018/06/20 4

[C#] foreach 가능한 객체 만들기

[C#] foreach 가능한 객체 만들기인덱서와 IEnumerable, IEnumerator 인터페이스를 활용하여 foreach가 가능한 객체를 만들수 있다.IEnumerableIEnumerator GetEnumerator() : IEnumerator 형식의 객체를 반환IEnumeratorboolean MoveNext() : 다음 요소로 이동한다. 컬렉션의 끝을 지나면 false, 이동 성공하면 true 반환void Reset() : 컬렉션의 첫 번째 위치의 앞으로 이동.Object Current {get;} : 컬렉션의 현재 위치를 반환Item 클래스class Item { public string Name{get;set;} public int Count{get;set;} ​ public overrid..

아카이빙/C# 2018.06.20

[C#] 인덱서

[C#] 인덱서인덱서(Indexer)는 인덱스를 이용해서 객체 내의 데이터에 접근하게 해주는 프로퍼티이다.인덱서 선언class 클래스이름 { 한정자 인덱서형식 this[형식 index] { get { // index를 이용하여 내부 데이터 변환 } set { // index를 이용하여 내부 데이터 저장 } } }Item 클래스를 정의하고, Item 배열을 필드로 갖는 ItemList 클래스에 인덱서를 활용해보자Item 클래스class Item { public string Name{get;set;} public int Count{get;set;} ​ public override string ToString() { return string.Format("(Name : {0}, Count : {1})", Na..

아카이빙/C# 2018.06.20

[C#] System.Array

[C#] System.ArrayC#에서는 모든 타입이 객체이다.배열도 당연히 객체이며, 기반이되는 클래스는 System.Array 이다.ForEach()private static void Print(int value) { Console.Write("{0} ", value); } ​ private static void PrintArray(int[] arr) { Array.ForEach(arr, new Action(Print)); Console.WriteLine(); } ​ static void Main() { int[] arr = {90, 65, 72, 88, 73, 91, 63}; PrintArray(arr); }배열의 모든 요소에 동일한 작업을 수행할 수 있다.Sort(), Reverse()Array...

아카이빙/C# 2018.06.20

[C#] 프로퍼티

[C#] 프로퍼티클래스를 작성하다보면 private 필드를 선언해야할 경우가 많다.이 private 필드를 다른 클래스에서 접근하게 하려면 getter, setter 메소드를 따로 정의해 줘야 하는 데 여간 귀찮은 일이 아닐 수 없다.class MyClass { private int myInt; public int GetMyInt() { return myInt; } public void SetMyInt(int newInt) { this.myInt = newInt; } } ​ class MainApp { static void Main() { MyClass instance = new MyClass(); instance.SetMyInt(5); ​ Console.WriteLine(instance.GetMyInt..

아카이빙/C# 2018.06.20