programming c sharp 3rd ch6 7 21
DESCRIPTION
publisher O'Reilly, Programming C#, 3rd Edition,TRANSCRIPT
Programming C#, 3rd EditionIntroduction (part 1)
寶來 資工部 簡伯松PoSung Chien (Poisson)
Agenda
• Operator overloading運算子的多載
• Structs 結構
• Streams資料流
CHAPTER 6Operator overloading
運算子的分類• Arithmetic operators ( 算數運算 )• Comparison operators / Relational operators
( 比較運算 )• Logical operators ( 邏輯運算 )• Bitwise operators ( 位元運算 )• Compound-assignment operators ( 複合賦值 )• Member and pointer operators ( 成員及指標 )• Other operators ( 其它 )
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
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
Logical operators ( 邏輯運算 )
Operator name Syntax Overloadable
Logical negation (NOT) !a Yes
Logical AND a && b Yes
Logical OR a || b Yes
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
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
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
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
Unsafe
• unsafe void Func () {
// Unsafe context: can use pointers here.
}
• void Func () {unsafe {
// Unsafe context: can use pointers here.
}}
運算子多載• 使用者可自行定義運算子
Stocks A = new Stocks();Stocks B = new Stocks();
A + B = ?
int add = 100 + 200;
DEMO
專案 PresentationTopic3 (operator_overloading) VS 2005
Arithmetic operatorsComparison operatorsConversion Operators
Operator pair define
• 當運算子 == 定義時,編譯器會要求運算子 != 也必需被定義。 (error)
• 當運算子 == 定義時,編譯器會暗示需要覆寫 Equals 函式。 (warning)
運算子多載的缺點• 混淆直覺
– 看似簡單的用法,其實耗時又複雜
• 容易誤用– 數量多時容易交叉誤用
CHAPTER 7structs
Structs
• 輕量型的資料包裝• 與 Class 非常相似• 不能繼承 class, struct• 不能定義解構 deconstructor• 不能定義 default constructor• 不能宣告 field 時就給值• 成員不能宣告為 protected• 可以繼承實作 interface• Class 是 Reference type
而 Struct 是 Value type
Structs 定義• [attributes] struct identifier [:interfaces-list]
{ body }
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
Creating structs without new
• 原本 struct abc = new struct();• 不用 new 的方法 struct abc;
CHAPTER 21streams
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
Working with Directories
• Directory class 成員均為 static• DirectoryInfo class 成員均不為 static
• 針對同一目錄多次操作, DirectoryInfo 會有較好的效能。因為 DirectoryInfo 並不會每次的操作都做 security privileges check ( 權限檢查 ) 。
• Namespace – Using System.IO;
Directory class methods
• CreateDirectory()• GetCreationTime()
SetCreationTime()• GetLastAccessTime()
SetLastAccessTime() • GetLastWriteTime()
SetLastWriteTime()
• GetLogicalDrives()• GetParent()• GetDirectoryRoot()• GetFiles()• Move()• Exists
DirectoryInfo class methods
• Name• Parent• Root• Create()• CreateSubdirectory()• Delete()
• EnumerateDirectories()• EnumerateFiles() • GetDirectories()• GetFiles()• GetFileSystemInfos()• MoveTo()• Refresh()
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
DEMO專案 PresentationTopic3_IO (DirectoryAccess) VS 2005
Working with Files
• File class 成員均為 static• FileInfo class 成員均不為 static
Experiment environment
• 針對同一檔案讀取 1000 次
• 對 1000 個不同檔案各讀取 1 次
• 比較 File 與 FileInfo 所花總時間差異
• 專案 PresentationTopic3_IO (DataSetsGenerator)• 專案 PresentationTopic3_IO (FileTest)
Performance of reading File
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.
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.
Binary Files
• BinaryReader / BinaryWriter 用在不知道檔案是否為單純的文字檔。
Buffered Streams
• 增加緩衝區,減少呼叫 System Call 的次數。
• 如果總是存取大於內部緩衝區大小, BufferedStream 可能無法配置緩衝區。
• BufferedStream must be initialized by some other existing Stream.
• 一般檔案存取已經是使用緩衝區,如 StreamReader/StreamWriter.
實作 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);
實作 buffered I/O (cont.)
• while ( (bytesRead = bufferedInput.Read(buffer,offset,SIZE_BUFF)) > 0 ) {
// 讀取後寫入 bufferedOutput.Write(
buffer,offset,bytesRead);}
• bufferedOutput.Flush( );• bufferedInput.Close( );• bufferedOutput.Close( );
Working with Text Files
• 讀取文字檔可使用 StreamReader 和StreamWriter 較為方便容易。
DEMO專案 PresentationTopic3_IO (BinaryStream) VS 2005
Thanks for attention