PowerPoint Presentation

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "PowerPoint Presentation"

Transcription

1

2 C#

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

4 C# 과닷넷프레임워크 CIL (1) (Common) Intermediate Language Managed Native IL 기계어 C# C++

5 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

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

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

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

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

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

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

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

13 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;

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

15 C# 2.0 -?? 연산자 string txt = null; if (txt == null) Console.WriteLine("(null)"); else Console.WriteLine(txt); string txt = null; Console.WriteLine(txt?? "(null)"); IL BCL 언어표현 - - O

16 C# 2.0 yield return/break (1) IEnumerable 의단축표기 F# C# 주요특징 list IList, ICollection 요소의전체목록을보유 sequence IEnumerable 필요한순간에요소의값을계산 IL BCL 언어표현 - - O

17 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;

18 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;

19 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++;

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

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

22 C# 2.0 익명메서드 (1) 이름없는메서드정의가능 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(); IL BCL 언어표현 - - O

23 C# 2.0 익명메서드 (2) delegate 타입의인자로인라인메서드정의 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");

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

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

26 C# 2.0 제네릭 (1) C++ 의 template 과유사 public class NewStack<T> 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]; IL BCL 언어표현 O - -

27 C# 2.0 제네릭 (2) 메서드수준의제네릭도지원 public class LogOutput public void Output<T,V>(T value1, V value2) Console.WriteLine(value1 + : + value2);

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

29 제약 1 상속타입 C# 2.0 제네릭 (4) public static T Max<T>(T item1, T item2) where T : IComparable if (item1.compareto(item2) >= 0) return item1; return item2;

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

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

32 C# 2.0 제네릭 (7) 기존컬렉션의제네릭버전제공.NET 1.x 컬렉션 ArrayList List<T> 대응되는제네릭버전의컬렉션 Hashtable Dictionary<TKey, TValue> SortedList SortedDictionary<TKey, TValue> Stack Stack<T> Queue Queue<T>

33 C# 2.0 Nullable 타입.NET 2.0 BCL: Nullable<T> 구조체추가 C# 의경우 T? 형태로단축표기 int? value1 = null; short? value2 = 5; // Nullable<int> value1; // Nullable<short> value2; if (value1.hasvalue) Console.WriteLine(value1); Console.WriteLine(value2); // Console.WriteLine(value2.Value); IL BCL 언어표현 - O O

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

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

36 C# 3.0 자동구현속성 (1) Field + Property 구현을단순화 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; IL BCL 언어표현 - - O

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

38 C# 3.0 컬렉션초기화 ICollection 인터페이스를구현한타입 컬렉션의요소를 new 구문에서추가 List<int> numbers = new List<int>(); numbers.add(0); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); List<int> numbers = new List<int> 0, 1, 2, 3, 4 ; IL BCL 언어표현 - - O

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

40 C# 3.0 LINQ (1) LINQ: Language-INtegrated Query 언어에통합된쿼리표현식 (Query Expressions) List<Person> people = new List<Person> new Person Name = "Anders", Age = 47, Married = true, new Person Name = "Hans", Age = 25, Married = false, ; IEnumerable<Person> all = from person in people select person; foreach (Person item in all) Console.WriteLine(item); IL BCL 언어표현 - O O

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

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

43 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 ; IL BCL 언어표현 - - O

44 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 ;

45 C# 3.0 객체초기화 (4) 컬렉션초기화 + 객체초기화 List<Person> list = new List<Person> new Person Name = "Ally", Age = 35, new Person Name = "Luis", Age = 40, ;

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

47 LINQ - SELECT C# 3.0 익명타입 (2) 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);

48 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);

49 C# 3.0 확장메서드 (1) 정적메서드를마치인스턴스메서드처럼사용 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); IL BCL 언어표현 - - O

50 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);

51 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 ; );

52 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; );

53 C# 3.0 확장메서드 (5) SELECT * FROM people ORDER BY Age var all = from p in people orderby p.age select p; var all = people.orderby(delegate(person p) return p.age; ).Select (delegate(person p) return p; );

54 C# 3.0 람다식 (1) 추론을통해 delegate 익명메서드를개선 delegate void Functor(object obj); Functor logoutput = delegate(object obj) Console.Write(obj); ; Functor loglambda = (obj) => Console.Write(obj); ; IL BCL 언어표현 - - O

55 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;

56 C# 3.0 람다식 (3) 메서드기반쿼리를단순화 var all = people.select(delegate(person p) return p; ); var all = people.select(p => p); var all = people.select(delegate(person p) return new Name = p.name, Age = p.age ; ); var all = people.select(p => new Name = p.name, Age = p.age );

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

58 Expression Tree C# 3.0 람다식 (5) // 람다식본체의루트는 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

59 C# 3.0 람다식 (6) Expression Tree 컴파일 Expression<Func<int, int, int>> exp = (a, b) => a + b; var addfunc = exp.compile(); Console.WriteLine(addFunc(5, 6));

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

61 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<TValue>(Expression<Func<TValue>> propertyselector) if (PropertyChanged!= null) var memberexpression = propertyselector.body as MemberExpression; if (memberexpression!= null) PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));

62 LINQ to 표준쿼리연산자 C# 3.0 LINQ 정리

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

64 C# 4.0 선택적매개변수 선택적매개변수 명명된인자 dynamic

65 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"); IL BCL 언어표현 O - -

66 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

67 C# 4.0 명명된인자 인자의이름으로호출측에서값전달 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"); IL BCL 언어표현 - - O

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

69 C# 4.0 dynamic (2) 결국은 object 타입 using System; using System.Runtime.CompilerServices; using Microsoft.CSharp.RuntimeBinder; static void Main() dynamic d = 5; d.calltest(); class Program public static CallSite<Action<CallSite, object>> p Site1; static void Main() object d = 5; if (p Site1 == null) p Site1 = CallSite<Action<CallSite, object>>.create( Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "CallTest", null, typeof(program), new CSharpArgumentInfo[] CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) )); p Site1.Target(p Site1, d);

70 C# 4.0 dynamic (3) IronPython 과 C# 1. NuGet 콘솔을열고, 2. Install-Package IronPython 명령어실행 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' 문자열출력

71 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);

72 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<string> list = new List<string>(); scriptscope.setvariable("mylist", list); string code mylist.add('my') mylist.add('python') "; scriptengine.execute(code, scriptscope); foreach (var item in list) Console.WriteLine(item);

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

74 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); IL BCL 언어표현 - O O

75 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); static void Main(string[] args) AwaitRead() Console.ReadLine(); IL BCL 언어표현 - O O

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

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

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

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