C# in depth and xna in depth 2nd Edition

52
C# in Depth and XNA in Depth © 2012 Daramkun All Rights Reserved for CNU GROW and KGSHS

Transcript of C# in depth and xna in depth 2nd Edition

Page 1: C# in depth and xna in depth 2nd Edition

C# in Depthand

XNA in Depth© 2012 Daramkun All Rights Re-

servedfor CNU GROW and KGSHS

Page 2: C# in depth and xna in depth 2nd Edition

ContentsO Differents from 1st Edition

O C# in Depth

O XNA in Depth

O Q&A

Page 3: C# in depth and xna in depth 2nd Edition

Differents from 1st Edi-tion

Page 4: C# in depth and xna in depth 2nd Edition

DifferentsO Changed & Fixed

O All most of ex-plains.

O Property imple-ments.

O sealed Keyword example.

O AddedO LINQO Named Parame-

terO Lambda

O RemovedO Example worksO Accelerometer

Page 5: C# in depth and xna in depth 2nd Edition

C# in Depthforeach, using, as, is, lock, sealed, …

Page 6: C# in depth and xna in depth 2nd Edition

Depth - PropertyO 속성

O 외부에서 봤을 때는 멤버 변수의 형태를 띄지만 내부에서 봤을 때는 함수의 형태

O 속성을 사용하면 생기는 장점O 캡슐화 및 은닉화의 간결화

O 속성의 단점O 변수와 완전히 동일하게 사용할 수 없음

O ref, out 등을 사용할 수 없음

Page 7: C# in depth and xna in depth 2nd Edition

Depth - PropertyO 속성의 형태

접근지정자 자료형 속성이름{

접근지정자 get { return 값 ; }접근지정자 set { 변수 = value;}

}

O 코드 예public string Name{

get { return name; }set { name = value; }

}

Page 8: C# in depth and xna in depth 2nd Edition

Depth – class VS structO 클래스

O 레퍼런스로 접근O new …() -> 힙에 객체 생성 -> 간접 접근O 변수에 null 을 넣을 수 있음

O 구조체O 값으로 접근O new …() -> 스택에 객체 생성 -> 직접 접근O 변수에 null 을 넣을 수 없음

Page 9: C# in depth and xna in depth 2nd Edition

Depth – class VS structO 성능상의 차이

O 차이는 없으나 이론적으로 클래스가 조금 더 느림O 간접 접근 , 힙에 생성 등이 이유가 됨

O 기능적 차이O 기본적으로 하는 일은 같으나 용도가 다름O 한번만 사용하는 객체는 구조체로 구현하는

편이 좋음

Page 10: C# in depth and xna in depth 2nd Edition

Depth – class VS structO 문법적 차이

O 구조체O 생성자를 추가해도 기본 생성자를 만듦O 생성자 내에서는 반드시 모든 멤버 변수 값을

초기화해야 함O 어떤 객체의 속성의 속성의 자료형이 구조체일

경우 직접적인 값을 변경할 수 없음O C++ 에서의 일반 클래스와 포인터 클래스의

차이를 생각해보면 됨

Page 11: C# in depth and xna in depth 2nd Edition

Depth – class VS structO Nullable struct

O 어떻게 보면 구조체의 클래스화O null 을 넣을 수 있는 구조체의 구현

O 형태O 구조체이름 ? 변수명 ;

O Point? m_pos = null;

Page 12: C# in depth and xna in depth 2nd Edition

Depth – ref/outO 모든 클래스는 레퍼런스 접근

O 즉 , Call by Reference 로 매개변수를 넘기는 일이 잦음

O 하지만 변수 자체나 구조체를 매개변수로 넘기기 위해서 특별한 키워드가 필요

Page 13: C# in depth and xna in depth 2nd Edition

Depth – ref/outO Call by Reference 키워드

O refO 할당된 변수를 레퍼런스로 넘기는 키워드O 사용할 일이 많지 않음

O outO 레퍼런스로 일단 보낸 후 값을 받아오는 키워드O 구조체를 넘기는 경우 많이 씀

O 구조체에 미리 new …() 을 할 필요가 없음

Page 14: C# in depth and xna in depth 2nd Edition

Depth – as/isO Boxing 과 Unboxing

O 클래스의 형변환 시 발생하는 문제

O 객체를 스택으로 꺼내는 작업이 UnboxingO 객체를 힙으로 넣는 작업이 Boxing

O C 스타일의 형변환을 클래스 객체에 사용하면 발생하는 문제임

Page 15: C# in depth and xna in depth 2nd Edition

Depth – as/isO Boxing 과 Unboxing 이 왜 문제죠 ?

O Unboxing 과 Boxing 은 메모리를 스택과 힙 사이에서 복사하는 과정이므로 실행 비용이 큼

O 알게 모르게 성능을 깎아먹는 주 적

그리고 그냥 형태가 마음에 안 들어

Page 16: C# in depth and xna in depth 2nd Edition

Depth – as/isO as 연산자

O 클래스 형변환에서 Unboxing 을 일으키지 않는 연산자O 당연히 Unboxing 되지 않으니 Boxing 도

되지 않음O 자식 클래스를 부모 클래스로 형변환할 때

사용할 수 있음O 관계 없는 클래스는 형변환하지 않고 null 을

반환

Page 17: C# in depth and xna in depth 2nd Edition

Depth – as/isO as 연산자의 장단점

O 장점O 자료형 검사가 강화됨O 자연어와 형태가 비슷하여 읽기에 편함O Boxing 과 Unboxing 비용을 절감함

O 단점O 상속 관계에서만 사용 가능

O C/C++ 형태의 구조체 끼워 맞추기 불가능O Secure 코딩이 “반드시” 필수

O 자료형 틀리면 null 이 들어가므로 이에 대한 조치도 취해야 함

Page 18: C# in depth and xna in depth 2nd Edition

Depth – as/isO is 연산자

O 두 자료형이 연관 관계인지 알려주는 연산자O 반환 값은 bool (true, false)

O is 연산자의 장단점O 장점

O 자료형 검사가 강화됨O 자연어와 형태가 비슷하여 읽기에 편함

O 단점O 딱히 없음

Page 19: C# in depth and xna in depth 2nd Edition

Depth - foreachO 열거자 (IEnumerator) 가 구현된 자료를

처음부터 종료 시점까지 반복하는 문법

O 형태foreach( 자료형 변수 in 열거자변수 ){

코드 ;}

Page 20: C# in depth and xna in depth 2nd Edition

Depth - foreachO 열거자가 구현된 기본 제공 클래스 목록

O List<T>, Dictionary<T, T>, Queue<T>, Stack<T>, Array

O 그 외…

O 열거자 인터페이스O interface System.Collections.IEnumerable

O System.Collections.IEnumerator GetEnumerator();

Page 21: C# in depth and xna in depth 2nd Edition

Depth - foreachO foreach 의 장단점

O 장점O 대부분의 경우 for 보다 빠르다O 문장이 간결해진다

O 단점O 뒤로 되돌리거나 역순으로 반복할 수 없다O 잘못 다루면 Boxing/Unboxing 테러 당함O foeach 의 임시 변수는 const 이기 때문에 값

변경 불가능

Page 22: C# in depth and xna in depth 2nd Edition

Depth - usingO using 의 두 가지 용도

1. 해당 CS 파일에서 사용할 namespace 선언2. 사용 후 바로 제거될 코드 블록

1. using System;using System.Text;using System.Collections.Generic;

2. using(Brush b = new SolidBrush(Color.CornflowerBlue)){…}

Page 23: C# in depth and xna in depth 2nd Edition

Depth - usingO 2 의 목적으로 사용하는 경우 사용할

클래스에는 반드시 IDisposable 의 Dis-pose 함수가 구현되어야 함

O 해당 코드 블록이 끝나면 블록에서 사용한 변수는 없는 취급 함O 그렇다고 같은 이름의 변수가 같은 함수 내에

있으면 이미 있는 이름의 변수

Page 24: C# in depth and xna in depth 2nd Edition

Depth - usingO IDisposable

O 다 사용한 데이터를 명시적으로 삭제하기 위해 구현하는 인터페이스

O 데이터를 삭제할 수는 있으나 메모리에서 해당 클래스 객체가 사라지지는 않음

O 이 인터페이스를 구현한 클래스의 객체가 메모리에서 내려가더라도 Dispose 함수를 자동 호출하지 않음

Page 25: C# in depth and xna in depth 2nd Edition

Depth – sealedO 다른 클래스가 상속받지 못하도록 하고 싶은

클래스가 있어요O sealed 키워드를 붙여주세요

O 상속 금지를 아예 명시화 하는 키워드

O 절대로 상속을 할 필요가 없는 클래스는 키워드를 지정하는 것이 멘탈 건강에 이로움

Page 26: C# in depth and xna in depth 2nd Edition

Depth - sealedO sealed 의 사용법

접근지정자 sealed class 클래스이름{

…}

Page 27: C# in depth and xna in depth 2nd Edition

Depth - lockO 임계 영역 지정을 편리하게 만들어주는

키워드

O 지정한 변수를 사용하려는 다른 lock 블록을 잠시 대기하도록 만들어 줌O 자세한 이론은 운영체제 분야의 Mutex 참고

O 자주 사용하면 성능이나 로직에 좋지 않음

Page 28: C# in depth and xna in depth 2nd Edition

Depth - lockO lock 의 사용법

lock( 잠글 변수 ){

…}

Page 29: C# in depth and xna in depth 2nd Edition

Depth - SerializationO 직렬화

O 쉽게 말하면 객체를 문자열로 만들어주는 기능

O 사용할 클래스에 직렬화 속성을 미리 입혀주어야 사용 가능

O 직렬화 수행 시 직렬화 대상이 아닌 멤버 변수를 따로 설정할 수 있음

Page 30: C# in depth and xna in depth 2nd Edition

Depth - SerializationO 직렬화 준비

[Serializable()]class …{

}

O 직렬화 사용O 바이너리

O BinaryFormatter 클래스 사용O SOAP

O 전용 직렬화 / 반직렬화 클래스 사용

Page 31: C# in depth and xna in depth 2nd Edition

Depth - SerializationO 직렬화 예외 멤버 지정

[NonSerialized]접근지정자 자료형 변수명 ;

O 대체로 직렬화가 필요한 작업O 객체의 간편한 저장 / 불러오기 작업O 패킷 송수신O 그 외

Page 32: C# in depth and xna in depth 2nd Edition

Depth - LINQO C# 이 데이터 처리에 강력한 언어가 된 이유

O LINQ 질의 문법

O SQL 언어들의 자연어 형태의 질의어 문법을 차용한 문법

O 거의 모든 Collections 클래스에서 사용 가능

Page 33: C# in depth and xna in depth 2nd Edition

Depth - LINQO 자세한 설명을 하기에는 지면이 부족하므로 일부

예제로 대신함class Program{

static void Main ( string [] args ){

string [] a = { "a", "swd", "ab", "zxcvb", "abc", "abcd", "abcde", "xcdsa", "sa" };

IEnumerable<string> q = from b in awhere b.Length > 3 select b;

foreach ( string b in q )Console.WriteLine ( b );

}}

Page 34: C# in depth and xna in depth 2nd Edition

Depth - LINQO 예제 2class Program{

static void Main ( string [] args ){string [] a = { "a", "swd", "ab", "zxcvb", "abc", "abcd", "abcde", "xcdsa", "sa" };IEnumerable<string> q = from b in a where b.Length > 3 orderby b descending select b;foreach ( string b in q )Console.WriteLine ( b );}

}

Page 35: C# in depth and xna in depth 2nd Edition

Depth – Named Param-eter

O 함수 호출 시 매개 인자에 이름을 붙여주는 방법

O “ 왜 이 자리에 이 값을 넣는가”라는 생각을 줄일 수 있다는 장점이 존재O Objective-C 의 메서드 형태와 비슷O Ruby 는 1.9 에서부터 지원하던 문법O C# 은 4.0 부터 지원함

Page 36: C# in depth and xna in depth 2nd Edition

Depth – Named Param-eter

O 예제Color myColor = Color.FromArgb(

a: 255, r: 255, g: 0, b: 255);

O참고로 위 예제는 Named Parameter 를 포함한 인자 순서를 바꿔도 의도한 대로 작동 됨

Page 37: C# in depth and xna in depth 2nd Edition

Depth - LambdaO무명 함수

O delegate 로 무명 함수를 작성하는 것보다 Lambda 로 작성하는 것이 더 깔끔함

O 함수형 언어의 특징 중 하나인 Lambda 문법을 얻어온 결과임

O 따라서 C# 에는 두 가지의 무명 함수 작성 문법이 존재

Page 38: C# in depth and xna in depth 2nd Edition

Depth - LambdaO Lambda 의 형태

( 매개변수 ) =>{

…};

Page 39: C# in depth and xna in depth 2nd Edition

Depth - LambdaO Action 델리게이트

O 값을 반환하지 않는 함수를 저장하는 기본 제공 델리게이트

O 제네릭을 사용하여 매개변수 자료형을 지정할 수 있음

O Func 델리게이트O 값을 반환하는 함수를 저장하는 기본 제공 델리게이트

O 제네릭을 사용하여 매개변수 자료형을 지정할 수 있음

Page 40: C# in depth and xna in depth 2nd Edition

Depth – to DepthO Garbage 관리

O 모든 객체는 필연적으로 Garbage 가 됨

O Garbage 는 총 3 단계로 구분됨O 각 단계를 세대라고 말함

O 모든 객체는 0 세대에 만들어짐

O 오래 사용될 수록 높은 세대로 옮겨감

Page 41: C# in depth and xna in depth 2nd Edition

Depth – to DepthO Garbage 관리

O 단계 수가 높아질 수록 단기간에 메모리에서 제거될 확률이 낮아짐

O 한번 사용 후 버리는 클래스 객체라면 반드시 null 을 넣어주어 참조를 지워주어야 함

Page 42: C# in depth and xna in depth 2nd Edition

Depth – to Depth

0 세대

1 세대

2 세대

단기 저장 객체가장 빈번히 정리

장기 저장 객체가장 긴 간격으로 정리

Page 43: C# in depth and xna in depth 2nd Edition

XNA in DepthContent Pipeline, Effect, …

Page 44: C# in depth and xna in depth 2nd Edition

Depth - EffectO 셰이더

O 사용자 정의 렌더링 파이프라인O 렌더링 파이프라인은 기타 도서 및 자료 참고

O XNA 에서는 고정 파이프라인이 없음O 셰이더를 이용하여 행렬 및 효과 적용

O 사용자 정의 셰이더는 파일로부터 가져올 수 있음O fx 파일 등O 클래스는 ShaderEffect

Page 45: C# in depth and xna in depth 2nd Edition

Depth - EffectO Effect 의 Begin 과 End

O XNA Framework 1.0 ~ 3.1O Begin 함수와 End 함수 사이에 코드 작성

O XNA Framework 4.0O 그런거 없ㅋ음ㅋ

O XNA 는 기본 셰이더를 제공해줌O BasicEffect 클래스O 고정 파이프라인과 기능이 흡사

Page 46: C# in depth and xna in depth 2nd Edition

Depth – Content Pipe-line

O 모든 콘텐츠 파일들을 하나의 인터페이스로 가져오기 위한 구조O ContentManager 클래스를 이용하면

정의된 대부분의 파일을 읽어올 수 있음

O 콘텐츠 파일 가져오는 함수O T ContentManager.Load<T>(“…”);

Page 47: C# in depth and xna in depth 2nd Edition

Depth – Content Pipe-line

O Content Pipeline 기본 제공 파이프라인O TextureO ModelO SpriteFontO EffectO XACTO Sound EffectO …

Page 48: C# in depth and xna in depth 2nd Edition

Depth – Content Pipe-line

O 사용자 정의 콘텐트 파이프라인O 콘텐트 파이프라인 프로젝트에서 구현해야 할

클래스O ContentImporter<T>O ContentProcessor<T>O ContentTypeWriter<T>

O 게임 프로젝트에서 구현해야 할 클래스O ContentTypeReader<T>

O 반드시 본 게임 프로젝트에서 구현해야 하며 , 다른 프로젝트에서 구현하면 못찾음

Page 49: C# in depth and xna in depth 2nd Edition

Depth – Content Pipe-line

O 파이프라인 클래스 설명O ContentImporter

O원본 파일을 읽어오는 클래스O ContentProcessor

O 읽어온 원본 파일을 형식을 다듬어 Writer 로 보내는 클래스

O ContentTypeWriterO 다듬은 데이터를 XNB 로 저장하는 클래스

O ContentTypeReaderO XNB 를 읽어오는 클래스

Page 50: C# in depth and xna in depth 2nd Edition

Depth - GamePadO XNA 에서 사용할 수 있는 유일한 게임 특화 장치

O Xbox Wired/Wireless Controller

왼쪽 엄지 스틱

오른쪽 엄지 스틱D-패드

뒤로 버튼 시작 버튼

A/B/X/Y 버튼

LT/LB/RT/RB 버튼빅 버튼

Page 51: C# in depth and xna in depth 2nd Edition

Depth - GamePadO 게임 패드 제어 인터페이스

O Microsoft.Xna.GamePadO GetState(int)

O 입력 방법O 버튼 및 패드

O 해당 버튼의 Pressed/Released 확인O 스틱

O 스틱의 X, Y 좌표로 스틱 위치 확인

O 유의 사항O Windows Phone 7 에서는 Back 버튼만 사용 가능

Page 52: C# in depth and xna in depth 2nd Edition

C# in Depth and XNA in Depth 52

C# in Depth and XNA in Depth

O참고서적O C# in Depth

O Effective C# (Bill Wagner 저 )O XNA in Depth

O Microsoft® XNA™ Xbox360 과 윈도우를 위한 그래픽과 게임 프로그래밍 (Chad Carter 저 )

O 게임 프로그래머를 위한 기초 수학과 물리(Wendy Stahler 저 )