C# 강좌 Day-18 인덱서
Unity3D/C# 2021. 9. 1. 18:14인덱서에서는 클래스나 구조체의 인스턴스를 배열처럼 인덱싱할 수 있습니다. 인덱싱 값은 형식이나 인스턴스 멤버를 명시적으로 지정하지 않고도 설정하거나 검색할 수 있습니다. 인덱서는 해당 접근자가 매개 변수를 사용한다는 점을 제외하면 속성과 유사합니다.
https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/indexers/
using System;
using System.Collections;
namespace Step51
{
public enum eRacesOfStarCraft
{
Zerg, Protoss, Terran
}
public class RacesCollection2
{
eRacesOfStarCraft[] races = {
eRacesOfStarCraft.Zerg, eRacesOfStarCraft.Protoss, eRacesOfStarCraft.Terran
};
public int this[eRacesOfStarCraft race]
{
get {
return this.FindIndex(race);
}
}
public int FindIndex(eRacesOfStarCraft race)
{
for (int i = 0; i < this.races.Length; i++) {
if(this.races[i] == race)
{
return i;
}
}
return -1;
}
}
class RacesCollection {
string[] races = { "Zerg", "Protoss", "Terran" };
public int this[string race] {
get {
return this.FindIndex(race);
}
}
private int FindIndex(string race) {
for (int i = 0; i < this.races.Length; i++) {
if (race == this.races[i]) {
return i;
}
}
return -1;
}
}
public class Marine { }
public class MarineEnumerator : IEnumerator
{
private Marine[] marines;
private int pointer = -1;
public MarineEnumerator(Marine[] marines)
{
this.marines = marines;
}
public object Current => this.marines[this.pointer];
public bool MoveNext()
{
this.pointer++;
return this.pointer < this.marines.Length;
}
public void Reset()
{
this.pointer = -1;
}
}
public class MarineGroup : IEnumerable {
private Marine[] marines;
public Marine this[int i]
{
get { return this.marines[i]; }
set { this.marines[i] = value; }
}
public MarineGroup(Marine[] marines)
{
this.marines = new Marine[marines.Length];
for (int i = 0; i < marines.Length; i++) {
this.marines[i] = marines[i];
}
}
public IEnumerator GetEnumerator()
{
return new MarineEnumerator(this.marines);
}
}
class NameCollection
{
private string[] names;
public string this[int i] {
get { return this.names[i]; }
set { this.names[i] = value; }
}
public NameCollection(int capacity)
{
this.names = new string[capacity];
}
}
class Program
{
static void Main(string[] args)
{
//NameCollection collection = new NameCollection(5);
//collection[0] = "홍길동";
//Marine[] marines = {
// new Marine(),
// new Marine(),
// new Marine()
//};
//MarineGroup group = new MarineGroup(marines);
//var marine = group[2];
//Console.WriteLine(marine);
//foreach (var m in group) {
// Console.WriteLine(m);
//}
//RacesCollection collection = new RacesCollection();
//var index = collection["Zerg"];
//Console.WriteLine(index); //0
RacesCollection2 collection = new RacesCollection2();
var index = collection[eRacesOfStarCraft.Protoss];
Console.WriteLine(index); //1
}
}
}
'Unity3D > C#' 카테고리의 다른 글
C# 강좌 Day-21 대리자 (0) | 2021.09.07 |
---|---|
C# 강좌 Day-20 예외처리 (0) | 2021.09.07 |
C# 강좌 Day-17 컬렉션 (namespace,using) (0) | 2021.08.31 |
C# 강좌 Day-16 배열, foreach (0) | 2021.08.30 |
C# 강좌 Day-15 (속성) (0) | 2021.08.15 |