Introduction to JENNIFER | Aug, 2013. C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A.

Slides:



Advertisements
Similar presentations
Developer Knowledge Sharing Eric Sun Dec, What programming language did you learn in school and since then? Now, its time to refresh …
Advertisements

The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
1 Visual C# "Whidbey": Language Enhancements Anders Hejlsberg Distinguished Engineer Microsoft Corporation Anders Hejlsberg Distinguished.
.NET Framework Overview
10 dingen die je niet wist over C#. ALM ALM Ranger Microsoft Auteur Getrouwd Lezen C#
LINQ and Collections An introduction to LINQ and Collections.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
.NET 3.5 – Mysteries. NetFx Evolution NetFx 1.0 C# 1.0, VB 7.0, VS.NET NetFx 1.1 C# 1.1, VB 7.1, VS 2003 NetFx 2.0 C# 2.0, VB 8.0, VS 2005 NetFx 3.0 C#
Programming Dr. Abraham Most slides are from your textbook.
DEV340 Microsoft Visual C# Under the Covers: An In-Depth Look at C# 2.0 Anders Hejlsberg Distinguished Engineer Microsoft Corporation.
Managed Code Generics Language Integrated Query Dynamic + Language Parity C# VB 11.0 Windows Runtime + Asynchrony C# VB 7.0 C# VB.
LINQ Programming in C# LINQ CSE Prof. Roger Crawfis.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
Advanced .NET Programming I 13th Lecture
Arrays, Lists, Stacks, Queues Static and Dynamic Implementation Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
Self-Contained CLI Assemblies Dipl.-Inf. Bernhard Rabe Operating Systems & Middleware Group Hasso-Plattner-Institute University of Potsdam.
.NET 2.0 and Visual Studio 2005 SigWin Outline Language enhancements in C# Language enhancements in C# –Generics –Partial types –Anonymous methods.
Keith Elder Microsoft MVP
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Visual C# 2005: IDE Enhancements Dan Fernandez C# Product Manager
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
C# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
C# Introduction Part 1. Which Visual Studio Should I use? Any Express (2012, 2013…) or Community Edition 2013 Any full version.
[ISRAR ALI] Hammad Khan. The namespace keyword is used to declare a scope. Making software components reusable can result in naming collisions (two classes.
CSCI 3328 Object Oriented Programming in C# Chapter 8: LINQ and Generic Collections 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
Problems.Net Анатолий Крыжановский Обра. ООП 2 class Bar { } void Foo(object a) { Console.WriteLine("object"); } void Foo(object a, object b) { Console.WriteLine("object,
Object Oriented Programming Generic Collections and LINQ Dr. Mike Spann
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
Stack Usage with MS Visual Studio Without Stack Protection.
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET library developers : with knowledge of async/await in C# / VB interested in low-level.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList.
Effective C# 50 Specific Ways to Improve Your C# Item 12 ~ 13 Neo2012/07/25 1.
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
C# Present and Future Marita Paletsou Software Engineer.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
© Copyright SELA software & Education Labs Ltd Baruch Hirsch St.Bnei Brak Israel 1 בס " ד.
1 New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various © University of Linz, Institute for System.
ICS51 Introductory Computer Organization Accessing parameters from the stack and calling functions.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 7 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Advanced .NET Programming I 2nd Lecture
Outline Introduction to the Phalanger System
Frank McCown TechLunch Old Dominion University March 28, 2007
Future of C#
Advanced .NET Programming I 8th Lecture
Advanced .NET Programming I 7th Lecture
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
New Features of C# Kuppurasu Nagaraj Microsoft Connect 2016
CS360 Windows Programming
Introduction to C# AKEEL AHMED.
Computer Architecture and Assembly Language
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
Module 2 Variables, Assignment, and Data Types
Frank McCown TechLunch Old Dominion University March 28, 2007
Defining Interfaces using C#
Advanced .NET Programming I 9th Lecture
Advanced .NET Programming I 8th Lecture
Advanced .NET Programming I 3rd Lecture
Advanced .NET Programming I 6th Lecture
Computer Architecture and System Programming Laboratory
Presentation transcript:

Introduction to JENNIFER | Aug, 2013

C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A

C# 5.0 | C# 과 닷넷 프레임워크 – CIL (1) (Common) Intermediate Language IL C# 기계어 C++ ManagedNative

C# 5.0 | C# 과 닷넷 프레임워크 – CIL (2) HelloWorld 의 C# / IL 언어 using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World"); }.assembly extern mscorlib {.publickeytoken = (B7 7A 5C E0 89 ).ver 4:0:0:0 }.assembly helloworld {.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( ).custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( E 6F 6E F 6E F ).hash algorithm 0x ver 0:0:0:0 }.module helloworld.exe.imagebase 0x file alignment 0x stackreserve 0x subsystem 0x0003.corflags 0x class private auto ansi beforefieldinit ConsoleApplication1.Program extends [mscorlib]System.Object {.method private hidebysig static void Main(string[] args) cil managed {.entrypoint.maxstack 8 IL_0000: nop IL_0001: ldstr "Hello World" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ret }.method public hidebysig specialname rtspecialname instance void.ctor() cil managed {.maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret }

C# 5.0 | C# 과 닷넷 프레임워크 – CIL (3) 닷넷 언어를 만드는 2 가지 방법 1. 소스코드  CLI 표준에 정의된 바이너리를 직접 생성 2. 소스코드  IL 언어  ilasm.exe 를 이용해서 CLI 표준에 정의된 바이너리를 생성

C# 5.0 | C# 과 닷넷 프레임워크 – CIL (4) IL 에서만 가능한 표현 표현 ILC#VB.NET 리턴 값에 따른 메서드 오버로드 OXX [protected and internal] 접근자 OXX struct 에서 인자 없는 생성자 정의 OXX

C# 5.0 | C# 과 닷넷 프레임워크 – 컴파일 (1) 두 번의 컴파일 C# 소스코드  중간 언어 (Intermediate Language)  기계어 C# 컴파일러 JIT 컴파일러 릴리즈 디버그 릴리즈 디버그

C# 5.0 | C# 과 닷넷 프레임워크 – 컴파일 (2) 언어 컴파일러 생산된 IL 만 올바르다면 언어의 문법은 자유롭게 확장 가능 ex) VB.NET 의 Module 에 정의되는 전역 변수 JIT 컴파일러 실행 시 IL 코드를 Debug / Release 모드에 따라 기계어로 변환 ex) Field 로 정의하면 Property get/set 으로 정의하는 것보다 빠른가 ? ex) 무한 재귀호출이 항상 StackOverflowException 을 발생할까 ?

C# 5.0 | C# 과 닷넷 프레임워크 – 버전 C# 과 닷넷 프레임워크 버전 관계 닷넷 버전 C# 버전주요 특징 1.0 ~ C# Generics 3.0 ~ LINQ 4.0 dynamic 예약어 async/await 예약어

C# 5.0 | C# 언어의 발전 요소 CLR – 2.0(4.0) 신규 IL BCL (Base Class Library) 언어 표현 - Syntactic Sugar ( 단축 표기 ) - 기존의 IL 표현력 추가 ILBCL 언어 표현 ---

C# 5.0 | C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A

C# 5.0 | C# 1.0 VM 언어지만 Interop 을 고려  PInvoke, unsafe(pointer), delegate ex) CPU 기계어 코드를 호출할 수 있을까 ? #include "stdafx.h" void getCpuId(int bits[]) { _asm { xor ebx, ebx; xor ecx, ecx; xor edx, edx; mov eax, 0; cpuid; mov edi, bits; mov dword ptr [edi + 0], eax; mov dword ptr [edi + 4], ebx; mov dword ptr [edi + 8], ecx; mov dword ptr [edi + 12], edx; } int _tmain(int argc, _TCHAR* argv[]) { int bits[4]; getCpuId(bits); printf("%x, %x, %x, %x\n", bits[0], bits[1], bits[2], bits[3]); return 0; }

C# 5.0 | C# 2.0 ?? 연산자 yield return/break partial class anonymous method static class 제네릭 (Generics) Nullable

C# 5.0 | C# ?? 연산자 ILBCL 언어 표현 --O string txt = null; if (txt == null) { Console.WriteLine("(null)"); } else { Console.WriteLine(txt); } string txt = null; Console.WriteLine(txt ?? "(null)");

C# 5.0 | C# 2.0 – yield return/break (1) IEnumerable 의 단축 표기 F#C# 주요 특징 listIList, ICollection 요소의 전체 목록을 보유 sequenceIEnumerable 필요한 순간에 요소의 값을 계산 ILBCL 언어 표현 --O

C# 5.0 | C# 2.0 – yield return/break (2) IList / ICollection public class ListNatural { ArrayList GetNumbers(int max) { ArrayList list = new ArrayList(); for (int i = 1; i <= max; i++) { list.Add(i); } return list; }

C# 5.0 | C# 2.0 – yield return/break (3) IEnumerable public class SequenceNatural : IEnumerable, IEnumerator { int _current; public IEnumerator GetEnumerator() { _current = 0; return this; } public object Current { get { return _current; } } public bool MoveNext() { _current++; return true; } public void Reset() { _current = 0; } foreach (var item in new YieldNatural().GetNumbers()) { Console.WriteLine(item); if ((int)item == 10) { break; }

C# 5.0 | C# 2.0 – yield return/break (3) yield return/break public class YieldNatural { public IEnumerable GetNumbers() { int n = 1; while (true) { yield return n; // if (n == 100) yield break; n++; } } }

C# 5.0 | C# 2.0 – partial type (1) 클래스의 구현을 2 개 이상으로 분리 ILBCL 언어 표현 --O partial class MyClass { public void Do() { Console.Write(_number); } partial class MyClass { private int _number = 1; } partial class MyClass { public void Do() { Console.Write(_number); } private int _number = 1; }

C# 5.0 | C# 2.0 – partial type (2) 자동 코드 생성의 문제점 해결 ! -Visual Studio 2002/2003  2005 F# 은 WPF 를 왜 지원하지 않는가 ?

C# 5.0 | C# 2.0 – 익명 메서드 (1) 이름 없는 메서드 정의 가능 ILBCL 언어 표현 --O static void Main(string[] args) { Thread t = new Thread(func); t.Start(); } private static void func(object obj) { Console.Write("..."); } static void Main(string[] args) { Thread t = new Thread( delegate (object obj) { Console.Write("..."); } ); t.Start(); }

C# 5.0 | C# 2.0 – 익명 메서드 (2) using System; namespace ConsoleApplication1 { class Program { delegate void Functor(object obj); static void Main(string[] args) { Functor logOutput = delegate(object obj) { Console.Write(obj); }; logOutput("test"); } delegate 타입의 인자로 인라인 메서드 정의

C# 5.0 | C# 2.0 – 익명 메서드 (3) 이벤트 처리기 this.textBox1.TextChanged += delegate (object sender, EventArgs e) { Console.WriteLine(“Do!”); }; // 또는 delegate 의 인자를 사용하지 않는다면 생략 가능 this.textBox1.TextChanged += delegate { Console.WriteLine(“Do!”); };

C# 5.0 | C# 2.0 – static class IL 코드 표현 : 상속 불가능한 추상 클래스 C# 컴파일러 : 인스턴스 멤버 정의 불가능 ILBCL 언어 표현 --O abstract class AbstractClass { } static class StaticClass { }.class private abstract auto ansi beforefieldinit AbstractClass extends [mscorlib]System.Object {.method family hidebysig specialname rtspecialname instance void.ctor() cil managed { }.class private abstract auto ansi sealed beforefieldinit StaticClass extends [mscorlib]System.Object { }

C# 5.0 | C# 2.0 – 제네릭 (1) C++ 의 template 과 유사 ILBCL 언어 표현 O-- public class NewStack { T [] _objList; int _pos; public NewStack(int size) { _objList = new T[size]; } public void Push(T newValue) { _objList[_pos] = newValue; _pos++; } public T Pop() { _pos--; return _objList[_pos]; }

C# 5.0 | C# 2.0 – 제네릭 (2) 메서드 수준의 제네릭도 지원 public class LogOutput { public void Output (T value1, V value2) { Console.WriteLine(value1 + “: ” + value2); }

C# 5.0 | C# 2.0 – 제네릭 (3) 박싱 / 언박싱 문제를 해결 ArrayList list = new ArrayList(); list.Add(5); // void Add(object value) list.Add(6); List list = new List (); list.Add(5); // void Add(T item) list.Add(6); //  void Add(int item);

C# 5.0 | C# 2.0 – 제네릭 (4) 제약 1 – 상속 타입 public static T Max (T item1, T item2) where T : IComparable { if (item1.CompareTo(item2) >= 0) { return item1; } return item2; }

C# 5.0 | C# 2.0 – 제네릭 (5) 제약 2 – 값 / 참조 타입 public static void Print (T item1, V item2) where T : struct where V : class { Console.WriteLine(item1); if (item2 != null) // 값 형식인 item1 과 비교한다면 컴파일 에러 { Console.WriteLine(item2); }

C# 5.0 | C# 2.0 – 제네릭 (6) 제약 3 – 인자 없는 생성자 필수 public static T AllocateIfNull (T item) where T : class, new() { if (item == null) { item = new T(); } return item; }

C# 5.0 | C# 2.0 – 제네릭 (7) 기존 컬렉션의 제네릭 버전 제공.NET 1.x 컬렉션대응되는 제네릭 버전의 컬렉션 ArrayListList HashtableDictionary SortedListSortedDictionary Stack Queue

C# 5.0 | C# 2.0 – Nullable 타입.NET 2.0 BCL: Nullable 구조체 추가 C# 의 경우 T? 형태로 단축 표기 ILBCL 언어 표현 -OO int? value1 = null; // Nullable value1; short? value2 = 5; // Nullable value2; if (value1.HasValue) { Console.WriteLine(value1); } Console.WriteLine(value2); // Console.WriteLine(value2.Value);

C# 5.0 | C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A

C# 5.0 | C# 3.0 자동 구현 속성 컬렉션 초기화 LINQ var 객체 초기화 익명 타입 확장 메서드 람다 식

C# 5.0 | C# 3.0 – 자동 구현 속성 (1) Field + Property 구현을 단순화 ILBCL 언어 표현 --O class Person { string _name; public string Name { get { return _name; } set { _name = value; } } int _age; public int Age { get { return _age; } set { _age = value; } } public string Name { get; set; } public int Age { get; set; }

C# 5.0 | C# 3.0 – 자동 구현 속성 (2) get/set 의 접근 제한자 class Person { public string Name { get; protected set; } public int Age { get; private set; }

C# 5.0 | C# 3.0 – 컬렉션 초기화 ICollection 인터페이스를 구현한 타입 컬렉션의 요소를 new 구문에서 추가 ILBCL 언어 표현 --O List numbers = new List (); numbers.Add(0); numbers.Add(1); numbers.Add(2); numbers.Add(3); numbers.Add(4); List numbers = new List { 0, 1, 2, 3, 4 };

C# 5.0 | C# 3.0 – LINQ 발음 : LINK? LIN-Q? 둘 다 옳다. “Moq” 도 “mock” 으로 발음하기도 하지만 “mock u” 로 발음하는 것처럼, 일반적으로 “link” 라고 발음하지만 “link u” 로 발음하기도 함. 주의 사항 : FAQ 에 대해서까지 이 규칙을 적용해서는 안됨 ( 출처 :

C# 5.0 | C# 3.0 – LINQ (1) LINQ: Language-INtegrated Query  언어에 통합된 쿼리 표현식 (Query Expressions) List people = new List { new Person { Name = "Anders", Age = 47, Married = true }, new Person { Name = "Hans", Age = 25, Married = false }, }; IEnumerable all = from person in people select person; foreach (Person item in all) { Console.WriteLine(item); } ILBCL 언어 표현 -OO

C# 5.0 | C# 3.0 – LINQ (2) SQL 쿼리의 SELECT 와 유사 방식코드 SQL SELECT * FROM people LINQ IEnumerable all = from person in people select person; 메서드 IEnumerable SelectFunc(List people) { foreach (Person item in people) { yield return item; }

C# 5.0 | C# 3.0 – var 예약어 컴파일러가 로컬 변수의 형식을 추론 C++ 11 의 auto 예약어와 동격 IEnumerable all = from person in people select person; var all = from person in people select person; foreach (var item in all) { Console.WriteLine(item); } ILBCL 언어 표현 --O

C# 5.0 | C# 3.0 – 객체 초기화 (1) 공용 속성을 통해 객체 생성 시에 초기화 class Person { public string Name { get; set; } public int Age { get; set; } } Person p1 = new Person(); p1.Name = “Hans”; p1.Age = 30; Person p2 = new Person { Name = "Tom", Age = 29 }; ILBCL 언어 표현 --O

C# 5.0 | C# 3.0 – 객체 초기화 (2) SELECT * FROM people  SELECT Name, Age FROM people  SELECT Name, Married FROM people var all = from person in people select person; var all = from person in people select new Person { Name = person.Name, Age = person.Age }; var all = from person in people select new Person { Name = person.Name, Married = person.Married };

C# 5.0 | C# 3.0 – 객체 초기화 (4) 컬렉션 초기화 + 객체 초기화 List list = new List { new Person { Name = "Ally", Age = 35 }, new Person { Name = "Luis", Age = 40 }, };

C# 5.0 | C# 3.0 – 익명 타입 (1) 이름 없는 타입  내부적인 처리는 익명 메서드와 유사 var 사용은 필수 var p = new { Count = 10, Title = "Anders" }; Console.WriteLine(p.Title + ": " + p.Count); ILBCL 언어 표현 --O

C# 5.0 | C# 3.0 – 익명 타입 (2) LINQ - SELECT var all = from person in people select new { Name = person.Name, Age = person.Age }; var all = from person in people select new { Name = person.Name, Married = person.Married }; foreach (var item in all) { Console.WriteLine(item); }

C# 5.0 | C# 3.0 – 익명 타입 (3) SELECT p.Name, p.Age, lang.Language FROM people as p INNER JOIN Language as lang ON p.Name = lang.Name var all = from p in people join lang in languages on p.Name equals lang.Name select new { Name = p.Name, Age = p.Age, Language = lang.Language }; foreach (var item in all) { Console.WriteLine(item); }

C# 5.0 | C# 3.0 – 확장 메서드 (1) 정적 메서드를 마치 인스턴스 메서드처럼 사용 ILBCL 언어 표현 --O class Program { static void Main(string[] args) { string txt = " string contents = txt.TextFromUrl(); Console.WriteLine(contents); } static class StringExtension { public static string TextFromUrl(this string txt) { WebClient wc = new WebClient(); return wc.DownloadString(txt); }

C# 5.0 | C# 3.0 – 확장 메서드 (2) 결국 정적 메서드 호출 class Program { static void Main(string[] args) { string txt = " string contents = StringExtension.TextFromUrl(txt); Console.WriteLine(contents); } static class StringExtension { public static string TextFromUrl(string txt) { WebClient wc = new WebClient(); return wc.DownloadString(txt); }

C# 5.0 | C# 3.0 – 확장 메서드 (3) 쿼리 구문과 메서드 기반 구문 var all = from p in people select p; var all = people.Select(delegate(Person p) { return p; }); var all = from p in people select new { Name = p.Name, Age = p.Age }; var all = people.Select(delegate(Person p) { return new { Name = p.Name, Age = p.Age }; });

C# 5.0 | C# 3.0 – 확장 메서드 (4) SELECT * FROM people WHERE Age >= 30 var all = from p in people where p.Age >= 30 select p; var all = people.Where (delegate(Person p) { return p.Age >= 30; }).Select(delegate(Person p) { return p; });

C# 5.0 | C# 3.0 – 확장 메서드 (5) SELECT * FROM people ORDER BY Age var all = people.OrderBy(delegate(Person p) { return p.Age; }).Select (delegate(Person p) { return p; }); var all = from p in people orderby p.Age select p;

C# 5.0 | C# 3.0 – 람다 식 (1) 추론을 통해 delegate 익명 메서드를 개선 ILBCL 언어 표현 --O delegate void Functor(object obj); Functor logOutput = delegate(object obj) { Console.Write(obj); }; Functor logLambda = (obj) => { Console.Write(obj); };

C# 5.0 | C# 3.0 – 람다 식 (2) 값 반환 + 단문 메서드  return+ 중괄호 생략 delegate int Calc(int v1, int v2); Calc addFunc = (v1, v2) => { return v1 + v2; }; Calc addLambda = (v1, v2) => v1 + v2;

C# 5.0 | C# 3.0 – 람다 식 (3) 메서드 기반 쿼리를 단순화 var all = people.Select(p => p); var all = people.Select(p => new { Name = p.Name, Age = p.Age }); var all = people.Select(delegate(Person p) { return p; }); var all = people.Select(delegate(Person p) { return new { Name = p.Name, Age = p.Age }; });

C# 5.0 | C# 3.0 – 람다 식 (4) 데이터로써의 람다  Expression Tree [ 데이터 ] Expression > exp = (a, b) => a + b; [mscorlib 어셈블리 ] public delegate TResult Func (T1 arg1, T2 arg2) [ 코드 ] Func exp = (a, b) => a + b;

C# 5.0 | C# 3.0 – 람다 식 (5) Expression Tree // 람다 식 본체의 루트는 2 항 연산자인 + 기호 BinaryExpression opPlus = exp.Body as BinaryExpression; Console.Write(opPlus.NodeType); // 출력 : Add // 2 항 연산자의 좌측 연산자의 표현식 ParameterExpression left = opPlus.Left as ParameterExpression; Console.Write(left.NodeType + ": " + left.Name); // 출력 : Parameter: a // 2 항 연산자의 우측 연산자의 표현식 ParameterExpression right = opPlus.Right as ParameterExpression; Console.Write(right.NodeType + ": " + right.Name); // 출력 : Parameter: b

C# 5.0 | C# 3.0 – 람다 식 (6) Expression Tree 컴파일 Expression > exp = (a, b) => a + b; var addFunc = exp.Compile(); Console.WriteLine(addFunc(5, 6));

C# 5.0 | C# 3.0 – 람다 식 (7) 사례 1) SQL 쿼리를 생성 Expression >> func = () => from p in people orderby p.Age descending select p; SELECT * FROM people ORDER BY Age DESC

C# 5.0 | C# 3.0 – 람다 식 (8) 사례 2) 공용 속성 이름 private int age = 0; public int Age { get { return age; } set { age = value; OnPropertyChanged(() => this.Age); //  OnPropertyChanged(“Age”); } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged (Expression > propertySelector) { if (PropertyChanged != null) { var memberExpression = propertySelector.Body as MemberExpression; if (memberExpression != null) { PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name)); }

C# 5.0 | C# 3.0 – LINQ 정리 LINQ to … 표준 쿼리 연산자

C# 5.0 | C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A

C# 5.0 | C# 4.0 – 선택적 매개 변수 선택적 매개변수 명명된 인자 dynamic

C# 5.0 | C# 4.0 – 선택적 매개 변수 (1) C++ 의 디폴트 매개 변수 class Person { public void Output(string name, int age = 0, string address = "Korea") { Console.Write(string.Format("{0}: {1} in {2}", name, age, address)); } class Program { static void Main(string[] args) { Person p = new Person(); p.Output("Anders"); p.Output("Winnie", 36); p.Output("Tom", 28, "Tibet"); } ILBCL 언어 표현 O--

C# 5.0 | C# 4.0 – 선택적 매개 변수 (2) 확장된 IL 구문.method public hidebysig instance void Output(string name, [opt] int32 age, [opt] string address) cil managed {.param [2] = int32(0x ).param [3] = "Korea".maxstack 8 IL_0000: nop...[ 생략 ]… IL_0019: ret }

C# 5.0 | C# 4.0 – 명명된 인자 인자의 이름으로 호출 측에서 값 전달 ILBCL 언어 표현 --O class Person { public void Output(string name, int age = 0, string address = "Korea") { Console.Write(string.Format("{0}: {1} in {2}", name, age, address)); } class Program { static void Main(string[] args) { Person p = new Person(); p.Output(address: "Tibet", name: "Tom"); p.Output(age: 5, name: "Tom", address: "Tibet"); p.Output(name: "Tom"); }

C# 5.0 | C# 4.0 – dynamic (1) 실행 시에 결정되는 타입 ILBCL 언어 표현 -OO using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { dynamic d = 5; int sum = d + 10; Console.WriteLine(sum); }

C# 5.0 | C# 4.0 – dynamic (2) 결국은 object 타입 using System; using System.Runtime.CompilerServices; using Microsoft.CSharp.RuntimeBinder; class Program { public static CallSite > p__Site1; static void Main() { object d = 5; if (p__Site1 == null) { p__Site1 = CallSite >.Create( Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "CallTest", null, typeof(Program), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); } p__Site1.Target(p__Site1, d); } static void Main() { dynamic d = 5; d.CallTest(); }

C# 5.0 | C# 4.0 – dynamic (3) IronPython 과 C# using System; using IronPython.Hosting; class Program { static void Main(string[] args) { var scriptEngine = Python.CreateEngine(); string code print 'Hello Python' "; scriptEngine.Execute(code); // 'Hello Python' 문자열 출력 } 1.NuGet 콘솔을 열고, 2.“Install-Package IronPython” 명령어 실행

C# 5.0 | C# 4.0 – dynamic (4) C# 에서 IronPython 메서드 연동 using System; using IronPython.Hosting; class Program { static void Main(string[] args) { var scriptEngine = Python.CreateEngine(); var scriptScope = scriptEngine.CreateScope(); string code def AddFunc(a, b): print 'AddFunc called' return (a + b) "; scriptEngine.Execute(code, scriptScope); dynamic addFunc = scriptScope.GetVariable("AddFunc"); int nResult = addFunc(5, 10); Console.WriteLine(nResult); }

C# 5.0 | C# 4.0 – dynamic (5) IronPython 에서 C# 메서드 연동 using System; using System.Collections.Generic; using IronPython.Hosting; class Program { static void Main(string[] args) { var scriptEngine = Python.CreateEngine(); var scriptScope = scriptEngine.CreateScope(); List list = new List (); scriptScope.SetVariable("myList", list); string code myList.Add('my') myList.Add('python') "; scriptEngine.Execute(code, scriptScope); foreach (var item in list) { Console.WriteLine(item); }

C# 5.0 | C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A

C# 5.0 | C# 5.0 – 호출자 정보 C++ 의 3 가지 매크로 상수에 대응 __FUNCTION__, __FILE__, __LINE__, using System; using System.Runtime.CompilerServices; class Program { static void Main(string[] args) { LogMessage(" 테스트 로그 "); } static void LogMessage(string text, [CallerMemberName] string member = "", [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { Console.WriteLine(" 텍스트 : " + text); Console.WriteLine(" 호출한 메서드 이름 : " + member); Console.WriteLine(" 호출한 소스코드의 파일명 : " + file); Console.WriteLine(" 호출한 소스코드의 라인번호 : " + line); } ILBCL 언어 표현 -OO

C# 5.0 | C# 5.0 – async/await (1) 마치 동기 방식처럼 비동기 호출 private static async void AwaitRead() { using (FileStream fs = new FileMode.Open)) { byte[] buf = new byte[fs.Length]; await fs.ReadAsync(buf, 0, buf.Length); string txt = Encoding.UTF8.GetString(buf); Console.WriteLine(txt); } ILBCL 언어 표현 -OO static void Main(string[] args) { AwaitRead() Console.ReadLine(); }

C# 5.0 | C# 5.0 – async/await (2) 비동기 호출 시 스레드 상태

C# 5.0 | C# 5.0 – async/await (3) 사용자 정의 …Async 메서드 private static async void FileReadAsync(string filePath) { string fileText = await ReadAllTextAsync(filePath); Console.WriteLine(fileText); } static Task ReadAllTextAsync(string filePath) { return Task.Factory.StartNew(() => { return File.ReadAllText(filePath); }); }

C# 5.0 | C# 5.0 1/1/ C# 과 닷넷 프레임워크 2/2/ C# 2.0, 3.0, 4.0, 5.0 정리 3/3/ 정리 및 Q&A

C# 5.0 | 정리 방식수 신규 IL 2 BCL 확장 5 언어 확장 18 단축 표기법 C# 6.0? Roslyn?