성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
[정성태] 만드실 수 있습니다. 단지, Unity 엔진 내의 스크립트와 W...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)</h1> <p> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# 9.0 - (1) <a target='tab' href='https://github.com/dotnet/csharplang/issues/100'>대상으로 형식화된 new 식(Target-typed new expressions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12363'>https://www.sysnet.pe.kr/2/0/12363</a> C# 9.0 - (2) <a target='tab' href='https://github.com/dotnet/csharplang/issues/1738'>localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12364'>https://www.sysnet.pe.kr/2/0/12364</a> C# 9.0 - (3) <a target='tab' href='https://github.com/dotnet/csharplang/issues/111'>람다 메서드의 매개 변수 무시(Lambda discard parameters)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12365'>https://www.sysnet.pe.kr/2/0/12365</a> C# 9.0 - (4) <a target='tab' href='https://github.com/dotnet/csharplang/issues/435'>원시 크기 정수(Native ints)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12366'>https://www.sysnet.pe.kr/2/0/12366</a> C# 9.0 - (5) <a target='tab' href='https://github.com/dotnet/csharplang/issues/1888'>로컬 함수에 특성 지정 가능(Attributes on local functions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12372'>https://www.sysnet.pe.kr/2/0/12372</a> C# 9.0 - (6) <a target='tab' href='https://github.com/dotnet/csharplang/issues/191'>함수 포인터(Function pointers)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12374'>https://www.sysnet.pe.kr/2/0/12374</a> C# 9.0 - (7) <a target='tab' href='https://github.com/dotnet/csharplang/issues/2850'>패턴 일치 개선 사항(Pattern matching enhancements)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12383'>https://www.sysnet.pe.kr/2/0/12383</a> C# 9.0 - (8) <a target='tab' href='https://github.com/dotnet/csharplang/issues/275'>정적 익명 함수 (static anonymous functions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12389'>https://www.sysnet.pe.kr/2/0/12389</a> C# 9.0 - (9) <a target='tab' href='https://github.com/dotnet/csharplang/issues/39'>레코드 (Records)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12392'>https://www.sysnet.pe.kr/2/0/12392</a> C# 9.0 - (10) <a target='tab' href='https://github.com/dotnet/csharplang/issues/2460'>대상으로 형식화된 조건식(Target-typed conditional expressions)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12399'>https://www.sysnet.pe.kr/2/0/12399</a> C# 9.0 - (11) <a target='tab' href='https://github.com/dotnet/csharplang/issues/2844'>공변 반환 형식(Covariant return types)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12402'>https://www.sysnet.pe.kr/2/0/12402</a> C# 9.0 - (12) <a target='tab' href='https://github.com/dotnet/csharplang/issues/3194'>foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)</a> ; https://www.sysnet.pe.kr/2/0/12403 C# 9.0 - (13) <a target='tab' href='https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/module-initializers.md'>모듈 이니셜라이저(Module initializers)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12404'>https://www.sysnet.pe.kr/2/0/12404</a> C# 9.0 - (14) <a target='tab' href='https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/extending-partial-methods.md'>부분 메서드에 대한 새로운 기능(New features for partial methods)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12405'>https://www.sysnet.pe.kr/2/0/12405</a> C# 9.0 - (15) <a target='tab' href='https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/top-level-statements.md'>최상위 문(Top-level statements)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12406'>https://www.sysnet.pe.kr/2/0/12406</a> C# 9.0 - (16) <a target='tab' href='https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/unconstrained-type-parameter-annotations'>제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)</a> ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/12423'>https://www.sysnet.pe.kr/2/0/12423</a> </pre> <br /> <hr style='width: 50%' /><br /> <br /> (이번 실습은 - 오늘 기준 16.7.7의 Visual Studio 2019에서 지원하지 않으므로 Visual Studio Preview 버전으로 실습해야 합니다.)<br /> <br /> 열거 가능한 타입을 만들려면 IEnumerable 인터페이스를 구현하기만 하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Collections; using System.Collections.Generic; class Program { static void Main(string[] args) { Computer my = new Computer(); <span style='color: blue; font-weight: bold'>foreach (Device device in my)</span> { Console.WriteLine(device.Name); } } } public <a target='tab' href='https://www.sysnet.pe.kr/2/0/12392'>record</a> Device { public string Name { get; init; } } <span style='color: blue; font-weight: bold'>public class Computer : IEnumerable<Device></span> { List<Device> _parts; public Computer() { _parts = new List<Device>() { new () { Name = "CPU"}, new () { Name = "MotherBoard"}, }; } public Device[] GetDevices() { return _parts.ToArray(); } <span style='color: blue; font-weight: bold'>public IEnumerator<Device> GetEnumerator()</span> { foreach (var device in GetDevices()) { yield return device; } } <span style='color: blue; font-weight: bold'>IEnumerator IEnumerable.GetEnumerator()</span> { yield return GetEnumerator(); } } #if !NET5_0 // .NET 5.0 환경이 아닌 경우 IsExternalInit 클래스를 별도로 정의해서 컴파일 가능하게 만듦 namespace System.Runtime.CompilerServices { public class IsExternalInit { } } #endif </pre> <br /> 하지만, 해당 인스턴스가 열거 가능한 타입인지 인터페이스를 이용한 체크를 할 필요가 없다면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > IEnumerable enumerable = my as IEnumerable; if (enumerable != null) { Console.WriteLine("Enumerable"); } /* if (my is IEnumerable) { Console.WriteLine("Enumerable"); } */ </pre> <br /> foreach 구문에 사용될 조건은 GetEnumerator라는 이름의 메서드만을 제공하기만 하면 됩니다. 따라서, 위의 Computer 코드를 다음과 같이 바꿔도 foreach에 그대로 사용할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public class Computer { List<Device> _parts; public Computer() { _parts = new List<Device>() { new Device() { Name = "CPU"}, new Device() { Name = "MotherBoard"}, }; } public Device[] GetDevices() { return _parts.ToArray(); } <span style='color: blue; font-weight: bold'>public IEnumerator<Device> GetEnumerator()</span> { foreach (var device in GetDevices()) { yield return device; } } } </pre> <br /> 또한, 위의 코드에서 GetEnumerator가 IEnumerator 인터페이스를 반환하는 데, 이것도 사실 강제 사항은 아닙니다. 단지, Current, MoveNext를 포함한 타입이면 되므로 다음과 같이 구현해도 여전히 코드는 잘 동작합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public class Computer { List<Device> _parts; public Computer() { _parts = new List<Device>() { new Device() { Name = "CPU"}, new Device() { Name = "MotherBoard"}, }; } public Device[] GetDevices() { return _parts.ToArray(); } public <span style='color: blue; font-weight: bold'>PartList GetEnumerator()</span> { return new PartList(this); } <span style='color: blue; font-weight: bold'>public class PartList</span> { Device [] _devices; public PartList(Computer computer) { _devices = computer.GetDevices(); } int _current = -1; <span style='color: blue; font-weight: bold'>public Device Current</span> { <span style='color: blue; font-weight: bold'>get</span> { return _devices[_current]; } } <span style='color: blue; font-weight: bold'>public bool MoveNext()</span> { if (_current >= _devices.Length - 1) { return false; } _current++; return true; } } } </pre> <br /> 또는 이런 식으로 포함해도 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public class Computer { List<Device> _parts; public Computer() { _parts = new List<Device>() { new Device() { Name = "CPU"}, new Device() { Name = "MotherBoard"}, }; } public Device[] GetDevices() { return _parts.ToArray(); } public <span style='color: blue; font-weight: bold'>Computer GetEnumerator()</span> { return <span style='color: blue; font-weight: bold'>this</span>; } int _current = -1; <span style='color: blue; font-weight: bold'>public Device Current</span> { <span style='color: blue; font-weight: bold'>get</span> { return _parts[_current]; } } <span style='color: blue; font-weight: bold'>public bool MoveNext()</span> { if (_current >= _parts.Count - 1) { return false; } _current++; return true; } } </pre> <br /> <br /> <hr style='width: 50%' /><br /> <br /> C# 9.0에서는 위의 구현에서 GetEnumerator 메서드의 구현을 <a target='tab' href='https://www.sysnet.pe.kr/2/0/438'>C# 3.0에 추가한 확장 메서드 유형</a>으로도 가능하게 되었습니다.<br /> <br /> 따라서, 기존 타입이 열거 가능한 유형이 아니었어도,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public class Computer { public Device[] GetDevices() { List<Device> list = new List<Device>() { new () { Name = "CPU"}, new () { Name = "MotherBoard"}, }; return list.ToArray(); } } </pre> <br /> 외부 개발자가 다음과 같이 GetEnumerator라는 이름의 확장 메서드를 추가만 해주면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > public static class ExtensionMethods { public <span style='color: blue; font-weight: bold'>static</span> IEnumerator<Device> GetEnumerator(<span style='color: blue; font-weight: bold'>this Computer computer</span>) { foreach (var device in computer.GetDevices()) { yield return device; } } } </pre> <br /> 좀 더 자연스럽게 foreach에 사용할 수 있게 되었습니다.<br /> <br /> 기억하실지 모르겠지만, 과거에 이런 식의 확장 메서드 사용이 한 번 있었습니다. ^^ 바로 C# 6.0의 "<a target='tab' href='https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-6#extension-add-methods-in-collection-initializers'>Extension Add methods in collection initializers</a>" 기능이 확장 메서드를 이와 같은 방식으로 활용한 첫 번째 사례입니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1652&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1934
(왼쪽의 숫자를 입력해야 합니다.)