programming c sharp 3rd ch6 7 21

40
Programming C#, 3rd Edition Introduction (part 1) 寶寶 寶寶寶 寶寶寶 PoSung Chien (Poisson)

Upload: alowblow

Post on 26-May-2015

654 views

Category:

Education


11 download

DESCRIPTION

publisher O'Reilly, Programming C#, 3rd Edition,

TRANSCRIPT

Page 1: Programming c sharp 3rd ch6 7 21

Programming C#, 3rd EditionIntroduction (part 1)

寶來 資工部 簡伯松PoSung Chien (Poisson)

Page 2: Programming c sharp 3rd ch6 7 21

Agenda

• Operator overloading運算子的多載

• Structs 結構

• Streams資料流

Page 3: Programming c sharp 3rd ch6 7 21

CHAPTER 6Operator overloading

Page 4: Programming c sharp 3rd ch6 7 21

運算子的分類• Arithmetic operators ( 算數運算 )• Comparison operators / Relational operators

( 比較運算 )• Logical operators ( 邏輯運算 )• Bitwise operators ( 位元運算 )• Compound-assignment operators ( 複合賦值 )• Member and pointer operators ( 成員及指標 )• Other operators ( 其它 )

Page 5: Programming c sharp 3rd ch6 7 21

Arithmetic operators ( 算數運算 )Operator name Syntax Overloadable

Basic assignment a = b No

Addition a + b Yes

Subtraction a - b Yes

Unary plus (integer promotion) +a Yes

Unary minus (additive inverse) -a Yes

Multiplication a * b Yes

Division a / b Yes

Modulo (remainder) a % b Yes

Increment ++a, a++ Yes

Decrement --a, a-- Yes

Page 6: Programming c sharp 3rd ch6 7 21

Comparison operators / Relational operators ( 比較運算 )

Operator name Syntax Overloadable

Equal to a == b Yes

Not equal to a != b Yes

Greater than a > b Yes

Less than a < b Yes

Greater than or equal to a >= b Yes

Less than or equal to a <= b Yes

Page 7: Programming c sharp 3rd ch6 7 21

Logical operators ( 邏輯運算 )

Operator name Syntax Overloadable

Logical negation (NOT) !a Yes

Logical AND a && b Yes

Logical OR a || b Yes

Page 8: Programming c sharp 3rd ch6 7 21

Bitwise operators ( 位元運算 )

Operator name Syntax Overloadable

Bitwise NOT ~a Yes

Bitwise AND a & b Yes

Bitwise OR a | b Yes

Bitwise XOR a ^ b Yes

Bitwise left shift a << b Yes

Bitwise right shift a >> b Yes

Page 9: Programming c sharp 3rd ch6 7 21

Compound-assignment operators ( 複合賦值 )

Operator name Syntax Overloadable

Addition assignment a += b Yes

Subtraction assignment a -= b Yes

Multiplication assignment a *= b Yes

Division assignment a /= b Yes

Modulo assignment a %= b Yes

Bitwise AND assignment a &= b Yes

Bitwise OR assignment a |= b Yes

Bitwise XOR assignment a ^= b Yes

Bitwise left shift assignment a <<= b Yes

Bitwise right shift assignment a >>= b Yes

Page 10: Programming c sharp 3rd ch6 7 21

Member and pointer operators ( 成員及指標 )

Operator name Syntax Overloadable

Array subscript a[b] Yes

Indirection ("variable pointed to by a") *a No

Reference ("address of a") &a No

Member b of object pointed to by a (unsafe) a->b No

Member b of object a a.b No

Member pointed to by b of object pointed to by a (unsafe) a->*b No

Member pointed to by b of object a (unsafe) a.*b No

Page 11: Programming c sharp 3rd ch6 7 21

Other operators ( 其它 )Operator name Syntax Overloadable

Function call See Function object. a(a1, a2) Yes

is operator object is string No

True / False true, false Yes

Ternary conditional a ? b : c No

Size-of sizeof(a)sizeof(type) No

Type identification typeof(a)typeof(type) No

Cast (implicit, explicit) (type) a Yes

Allocate storage new type No

Page 12: Programming c sharp 3rd ch6 7 21

Unsafe

• unsafe void Func () {

// Unsafe context: can use pointers here.

}

• void Func () {unsafe {

// Unsafe context: can use pointers here.

}}

Page 13: Programming c sharp 3rd ch6 7 21

運算子多載• 使用者可自行定義運算子

Stocks A = new Stocks();Stocks B = new Stocks();

A + B = ?

int add = 100 + 200;

Page 14: Programming c sharp 3rd ch6 7 21

DEMO

專案 PresentationTopic3 (operator_overloading) VS 2005

Arithmetic operatorsComparison operatorsConversion Operators

Page 15: Programming c sharp 3rd ch6 7 21

Operator pair define

• 當運算子 == 定義時,編譯器會要求運算子 != 也必需被定義。 (error)

• 當運算子 == 定義時,編譯器會暗示需要覆寫 Equals 函式。 (warning)

Page 16: Programming c sharp 3rd ch6 7 21

運算子多載的缺點• 混淆直覺

– 看似簡單的用法,其實耗時又複雜

• 容易誤用– 數量多時容易交叉誤用

Page 17: Programming c sharp 3rd ch6 7 21

CHAPTER 7structs

Page 18: Programming c sharp 3rd ch6 7 21

Structs

• 輕量型的資料包裝• 與 Class 非常相似• 不能繼承 class, struct• 不能定義解構 deconstructor• 不能定義 default constructor• 不能宣告 field 時就給值• 成員不能宣告為 protected• 可以繼承實作 interface• Class 是 Reference type

而 Struct 是 Value type

Page 19: Programming c sharp 3rd ch6 7 21

Structs 定義• [attributes] struct identifier [:interfaces-list]

{ body }

Page 20: Programming c sharp 3rd ch6 7 21

DEMO

專案 PresentationTopic3 (struct_default_constructor) VS 2005專案 PresentationTopic3 (struct_distructor) VS 2005專案 PresentationTopic3 (struct_inheritance) VS 2005專案 PresentationTopic3 (struct_interface) VS 2005專案 PresentationTopic3 (struct_nonew) VS 2005

Page 21: Programming c sharp 3rd ch6 7 21

Creating structs without new

• 原本 struct abc = new struct();• 不用 new 的方法 struct abc;

Page 22: Programming c sharp 3rd ch6 7 21

CHAPTER 21streams

Page 23: Programming c sharp 3rd ch6 7 21

Agenda• Working with Directories• Working with Files• Binary Files• Buffered Streams• Working with Text Files

• Next presentation• Serialization • Asynchronous I/O• Network I/O• Web Streams• Isolated Storage

Page 24: Programming c sharp 3rd ch6 7 21

Working with Directories

• Directory class 成員均為 static• DirectoryInfo class 成員均不為 static

• 針對同一目錄多次操作, DirectoryInfo 會有較好的效能。因為 DirectoryInfo 並不會每次的操作都做 security privileges check ( 權限檢查 ) 。

• Namespace – Using System.IO;

Page 25: Programming c sharp 3rd ch6 7 21

Directory class methods

• CreateDirectory()• GetCreationTime()

SetCreationTime()• GetLastAccessTime()

SetLastAccessTime() • GetLastWriteTime()

SetLastWriteTime()

• GetLogicalDrives()• GetParent()• GetDirectoryRoot()• GetFiles()• Move()• Exists

Page 26: Programming c sharp 3rd ch6 7 21

DirectoryInfo class methods

• Name• Parent• Root• Create()• CreateSubdirectory()• Delete()

• EnumerateDirectories()• EnumerateFiles() • GetDirectories()• GetFiles()• GetFileSystemInfos()• MoveTo()• Refresh()

Page 27: Programming c sharp 3rd ch6 7 21

Directory VS. DirectoryInfo

• Directory.CreateDirectory(path);• Directory.SetCreationTime(path,

createTime);• Directory.SetLastAccessTime(pat

h, lastAccessTime);• Directory.SetLastWriteTime(path,

lastWriteTime);• Directory.GetLogicalDrives()• Directory.GetParent(path)• Directory.GetDirectoryRoot(path)• Directory.GetFiles(path)• Directory.Move(path, newPath);• Directory.Exists(path)

• DirectoryInfo directoryInfo = new DirectoryInfo(path);

• directoryInfo.Create();• directoryInfo.CreationTime =

createTime;• directoryInfo.LastAccessTime =

lastAccessTime;• directoryInfo.LastWriteTime =

lastWriteTime;

• directoryInfo.Parent• directoryInfo.Root• directoryInfo.GetFiles()• directoryInfo.MoveTo(newPath);• directoryInfo.Exists

Page 28: Programming c sharp 3rd ch6 7 21

DEMO專案 PresentationTopic3_IO (DirectoryAccess) VS 2005

Page 29: Programming c sharp 3rd ch6 7 21

Working with Files

• File class 成員均為 static• FileInfo class 成員均不為 static

Page 30: Programming c sharp 3rd ch6 7 21

Experiment environment

• 針對同一檔案讀取 1000 次

• 對 1000 個不同檔案各讀取 1 次

• 比較 File 與 FileInfo 所花總時間差異

• 專案 PresentationTopic3_IO (DataSetsGenerator)• 專案 PresentationTopic3_IO (FileTest)

Page 31: Programming c sharp 3rd ch6 7 21

Performance of reading File

Page 32: Programming c sharp 3rd ch6 7 21

Reading or WritingClass Use

Stream Abstract class that supports reading and writing bytes.

BinaryReader/BinaryWriter

Read and write encoded strings and primitive datatypes to and from streams.

File, FileInfo, Directory, DirectoryInfo

Provide implementations for the abstract FileSystemInfo classes, including creating, moving, renaming, and deleting files and directories.

FileStream For reading to and from File objects; supports random access to files. Opens files synchronously by default; supports asynchronous file access.

TextReader,TextWriter, StringReader,StringWriter

TextReader and TextWriter are abstract classes designed for Unicode character I/O. StringReader and StringWriter write to and from strings, allowing your input and output to be either a stream or a string.

Page 33: Programming c sharp 3rd ch6 7 21

Reading or Writing (cont.)

Class Use

BufferedStream

A stream that adds buffering to another stream such as a NetworkStream. Note that FileStream has buffering built in. BufferedStreams can improve performance of the stream to which they are attached.

MemoryStream

A nonbuffered stream whose encapsulated data is directly accessible in memory. A MemoryStream has no backing store, and is most useful as a temporary buffer.

NetworkStream A stream over a network connection.

Page 34: Programming c sharp 3rd ch6 7 21

Binary Files

• BinaryReader / BinaryWriter 用在不知道檔案是否為單純的文字檔。

Page 35: Programming c sharp 3rd ch6 7 21

Buffered Streams

• 增加緩衝區,減少呼叫 System Call 的次數。

• 如果總是存取大於內部緩衝區大小, BufferedStream 可能無法配置緩衝區。

• BufferedStream must be initialized by some other existing Stream.

• 一般檔案存取已經是使用緩衝區,如 StreamReader/StreamWriter.

Page 36: Programming c sharp 3rd ch6 7 21

實作 buffered I/O

• Stream inputStream = File.OpenRead(@“C:\test\folder3.cs”);

• Stream outputStream = File.OpenWrite(@"C:\test\folder3.bak");

• BufferedStream bufferedInput = new BufferedStream(inputStream);

• BufferedStream bufferedOutput = new BufferedStream(outputStream);

Page 37: Programming c sharp 3rd ch6 7 21

實作 buffered I/O (cont.)

• while ( (bytesRead = bufferedInput.Read(buffer,offset,SIZE_BUFF)) > 0 ) {

// 讀取後寫入 bufferedOutput.Write(

buffer,offset,bytesRead);}

• bufferedOutput.Flush( );• bufferedInput.Close( );• bufferedOutput.Close( );

Page 38: Programming c sharp 3rd ch6 7 21

Working with Text Files

• 讀取文字檔可使用 StreamReader 和StreamWriter 較為方便容易。

Page 39: Programming c sharp 3rd ch6 7 21

DEMO專案 PresentationTopic3_IO (BinaryStream) VS 2005

Page 40: Programming c sharp 3rd ch6 7 21

Thanks for attention