Csharp Farsi
Csharp Farsi
09177112161
.
. .
www.IrPDF.com
)
( .
1-1 13NET .
-1-2-3 58if
-.NET1-1-1 14CLI
-2-2-3 59if
-3-2-3 62
-1-2-1 15NET .
17-CTS 2-2-1
-5-2-3 if 64
-3-2-1 18
-6-2-3 65switch
-8-2-3 switch 68
-3-3 69
-1-4-1 25NET.
-1-3-3 69goto
-2-4-1 25NET.
-3-4-1 29
-4-3-3 72for
-5-1 31C#
-4-3 77
-1-5-1 31
-1-4 80
-2-5-1 31
-2-4 80
-6-1 33
:-3-4 81 :
-1-2 36C#
-4-3 82 :
-1-1-2 37C#
-5-4 82
-2-2 39
-1-5-4 83
-3-2 42
-2-5-4 83
-1-3-2 42
-3-5-4 84
-2-3-2 43
-6-4 84
-4-2 44C#
-7-4 84
-1-4-2 44
-1-5 87
-2-4-2 45
-1-1-5 88
-5-2 45
-2-1-5 89Time
-1-5-2 46
-3-1-5 90
-2-5-2 47System.Enum
-2-5 91
-3-5-2 flag 47
-3-5 92
-6-2 48
-4-5 93
- System.Object1-6-2 48System.ValueType
-5-5 94this
-2-6-2 48
-6-5 95
-3-6-2 49
-1-6-5 96
-7-2 50
-2-6-5 98
-1-7-2 51using
-7-5 99
-2-7-2 52
-8-5 101
-8-2 53I/O
-9-5 104
-9-2 54
106
-1-3 57
106
-2-3 58
-1-6 106
-2-6 108
-5-10 153SortedList
-1-2-6 109
-6-10 154BitArray
-2-2-6 110
-7-10 157
-3-2-6 110
-8-10 157
-3-6 111
-9-10 157
-1-3-6 111
-1-11 158
-2-11 160
-4-6 115
-3-11 161
-5-6 117
-4-11 161
-6-6 ) ) 117Object
-5-11 163
-7-6 119
-1-5-11 164
120
-2-5-11 166
120
-3-5-11 / 166
-overload1-7 120
-6-11 166FCL
-2-7 122
-1-6-11 167
-1-2-7 124get
-7-11 170
-2-2-7 125set
-1-12 172
-3-7 125
-1-1-12 172
-1-3-7 126
-2-1-12 173
-2-12 174
-4-7 129
-3-12 175
-1-8 130
-4-12 176
-1-1-8 131
-5-12 177
-2-1-8 131
-1-13 179operator
-3-1-8 132
-2-13 179NET .
-2-8 133foreach
-3-13 179
-3-8 134
-4-13 180
-4-8 134params
-5-13 180
-5-8 135
-6-13 180
-1-5-8 135
-7-13 184
-2-5-8 137
-1-14 186
-6-8 140
-1-1-14 186
-7-8 140
-2-14 188Windows.Forms
-8-8 141
-1-2-14 188Control
-1-9 144
189control
-2-9 145
-2-2-14 190
-1-2-9 146
190
-2-2-9 146new
191
-3-9 148
Tab 192
-1-10 150ArrayList
193
-2-10 151Queue
-3-2-14 194Control
-3-10 152Stack
194
-4-10 152HashTable
196
- NET.
-3-14 198Form
-5-2-15 226Panel
1-3-14 199
-6-2-15 226FlowLayoutPanel
200
-7-2-15 227TableLayoutPanel
200
-8-2-15 228Label
202
-2-3-14 203
-1-3-15 228PictureBox
203modeless
-2-3-15 230TextBox
203
231
-3-3-14 204
-4-15 CheckedListBoxListBox
232ComboBox
204
-4-3-14 205
-1-4-15 232ListBox
206
232ListBox
206
233ListBox
-5-3-14 207
234ListBox
208MDI
-2-4-15 ComboBox :
236CheckedListBox
208MDI
MDI 210VS.NET
-4-14 211
-1-5-15 237ListView
-1-4-14 211MenuItem
237ListView
-2-4-14 211
237ListView
-3-4-14 212
238
-5-14 213
239ListView
-ToolTip1-5-14 213
239
-2-5-14 1F 214Help
240ListView
-3-5-14 216HelpProvider
240
-6-14 216
241
-1-6-14 216
241ListView
-2-6-14 217
-2-5-15 242TreeView
-Override3-6-36 217
242TreeNode
-4-6-14 218VS.NET
243
-7-14 218
244TreeView
244
TreeView 244
Label
222
-6-15 TimerProgressBar
-1-2-15 222Button
246
222
247StatusStrip
223Button
-7-15 248
-2-2-15 223CheckBox
-1-7-15 249
223CheckBox
-3-2-15 224RadioButton
249User Control
224
UserControl 250
-4-2-15 226GroupBox
UserControl 251
StatusStrip
-8-15 252
282ColorDialog
252
-6-16 283PrintDialog
254
284PrintDialog
254
284PrintDialog
-9-15 256
-1-6-16 284PrintDocument
-1-9-15 257
284PrintDocument
257
285
ResourceWriter
288
258Resources .
-7-16 291FolderBrowserDialog
ResourceManager
292FolderBrowser
258
292FolderBrowser
ResXResourceWriter
-8-16 294
259resx .
-1-17 297
ResXResourceReader
-1-1-17 299
259resx .
-2-1-17 299
resx. 259resources .
-2-17 303
-VS.NET2-9-15 259
-1-2-17 303
260
-2-2-17 304is
260VS.NET
-3-2-17 306as
261
-4-2-17 as 307is
261VS.NET
-5-2-17 307
-10-15 261
-override3-17 307
-1-16 263MessageBox
-4-17 310
264 :
-2-4-17 312
265 :
-3-4-17
265
312
265Show
-5-17 314
267
-1-18 316
-2-16 268OpenFileDialog
-1-1-18 317
269OpenFileDialog
-2-1-18 317
271OpenFileDialog
-3-1-18 317
271OpenFileDialog
-4-1-18 319
273
-2-18 321
-3-16 274SaveFileDialog
-1-2-18 322
274SavefileDialog
-2-2-18 322
275SaveFileDialog
-3-2-18 322
275SaveFileDialog
-3-18 323GUI
-4-16 277FontDialog
-1-19 325
277FontDialog
-2-19 326System.Exception
278FontDialog
-3-19 327
278FontDialog
-4-19 329
-5-16 280ColorDialog
-5-19 332
281ColorDialog
-1-20 333
- NET.
-1-1-20 334
-2-3-21 375
-2-1-20 335
-3-3-21 376
335char
-4-3-21 378
Char 335
-5-3-21 378
-3-1-20 335
378FileStream
-4-1-20 336
-6-3-21 380
-2-20 337
380StreamReader
-1-2-20 337
380StreamReader
-2-2-20 338
381StreamWriter
-3-2-20 339
381StreamWriter
-3-20 339
-7-3-21 381CryptoStream
-1-3-20 340String.Compare
-4-21 381
-2-3-20 341String.CompareOrdinal
-5-21 383
-4-20 342
-1-4-20 342
-2-4-20 343
-6-21 385
-3-4-20 343
-1-22 387
-4-4-20 345
388Access
-5-20 346StringBuilder
-3-22 394
400
-6-20 348
402-ADO.NET 2-23
-1-6-20 348
-1-2-23 403Data
-2-6-20 349
-2-2-23 404SqlConnection:
-3-6-20 350
404ring ConnectionSt
-4-6-20 352
-3-2-23 406SqlCommand
DateTimeFormatInfo
406Connection
406CommandText
352NumberFormatInfo
-7-20 353
407Parameters
-1-7-20 354Regex
408ExecuteNonQuery
-2-7-20 357
-4-2-23 409SqlDataAdapter
-3-7-20 361
409SelectCommand
-8-20 362
SelectCommand
-1-21 363
410
-1-1-21 364NET .
SelectCommand
-2-1-21 366Path
411
CommandBuilder SQL
-2-21 370
411
-1-2-21 370FilePeopertiesAndMovement
412Fill
-2-2-21
-5-2-23 413DataSet
FilePropertiesAndMovment
371
-6-2-23 414DataView
-3-21 374
415Sort
-1-3-21 374
415RowFilter
SQL
416Find
-3-1-26 484
-4-1-26 485System.Net
-5-1-26 485System.Net.Sockets
-4-23 422
-2-26 485TCP
422-CurrencyManager,BindingContext: 1-4-23
-1-2-26 487Net.
-2-4-23 423
-2-2-26 488
-5-23 437
-3-2-26 489
-1-24 440
-4-2-26 492
-1-1-24 440
-3-26 492UDP
-2-1-20 442
-1-3-26 492NET
-3-1-20 443Sleep
-2-3-26 493
-4-1-24 444
-3-3-26 494
-2-24 447
-4-3-26 495
-1-2-20 449Interlocked
-4-26 496UDP
-2-2-24 451
-1-4-26 496NET
-3-2-20 451
-2-4-26 498
-3-20 456
-3-4-26 500
-1-25 458WebClient
-4-4-26 503
-1-1-25 458
504
-2-1-25 458WebClient
-5-1-25 WebRequest
504Socket
WebResponse
461
505
-6-1-25 462
505
-2-25 463HTML
507
-1-2-25 463
507SocketOptionLevel
-2-2-25 465IE
507SocketOptionName
-3-2-25 IE
508SocketFlags
465
509SocketException
-4-2-25
510TCP
510TcpEchoClientSockets.cs
471WebBrowser
-5-2-25 472WebBrowser
-2-1-27 510Socket
-6-2-25 473
511TCP
-3-25 474Web
-3-1-27 512
-1-3-25 475
513UDP
URI 475
-4-1-27 514
-2-3-25 IP 475DNS
-I/O5-1-27 515
-6-1-27 516I/O
-4-3-25 477DNSLookup
-7-1-27 517
-4-25 478
Echo 519
-1-26 479
-8-1-27 520
-1-1-26 481TCP
)( Select 520Socket
-2-1-26 482UDP
521
- NET.
-I/O9-1-27 522
-1-2-30 566
525
-2-2-30 570
Tcp 527
-3-2-30 572
-1-28 529
-4-2-30 572
-1-1-28 530
-5-2-30 573DLL
-2-1-28 531
-3-30 573
-3-1-28 531
-1-3-30 573
-2-28 532MQ
574-GAC 2-3-30
-1-2-28 532
-3-3-30 574
-2-2-28 533
-4-3-30 576
534
578 1
534
578 2005#C
-3-28 535
580 2005#VC
-1-3-28 536
-2-3-28 536CourseOrder
536CourseOrder
538
539
540
543
543
544
-4-28 545MessageQueue
-5-28 545
-1-29 546ActiveX
-2-29 549NET .
-1-2-29 549
-2-2-29 550
-3-2-29 551
-3-29 552Com
-1-3-29 553ComTestForm
-2-3-29 COM DLL 554NET .
-3-3-29 554
-5-3-22 554
-4-29 558NET
-1-4-22 560
561-P/Invoke 5-29
-1-30 564PE
-1-1-30 564
-2-1-30 565
-3-1-30 565
-2-30 566
.NET C#
:NET.
:1CLR .
NET
: .
:FCL5 .
: .NET . ILdasm
) .JIT2 (.
WinCV .
:#C #C .
.
. #C .
.
.NET
FCL CLR
Platform
Platform .NET
1-1 NET.
NET. )(
. :
.
DLL .
Just In Time
- C# 09177112161 -
1
. #C NET.
ECMA3 .
CLI
.
NET.
CLR : FCL. 1-1 .
1-1
NET Framework.
)CLR CLI (
4 ) CLR (
CLR COM
API .
FCL . ) (
NET. . NET. .
NET. .
NET.-1-1-1 CLI
NET. #C :
Platform NET.
C#.NET CLI
.
CLI Platform .
.
14
CIL
CLI
Portable
Type Safety
- NET.
. 1 CLI .
.
CLI #C
(Fortran,Pascal,Pythen,Defacto).
NET. 1 1 CLI .
CLI . CLI 2-1
.
2-1 CLI
.
NET.
.
CLR -2-1
CLR . .
. .
. CLR
. .
-1-2-1 NET.
CLR CPU .
CIL IL . MSIL
DLL
EXE .
. ,JIT
IL
) . ( . CLR IL
NET. . 3-1
CLR
Type System
15
- C# 09177112161 -
. IL . IL
.
1-3 CLR
JIT
4 .
. JIT .
5 .
NET. . 6
. .
16
Localizing
Metadata
Self descriptive
Meta code
Garbage Collection
Reflection
- NET.
IL .
NET.
. IL
32 .
.
CLI CTS CLR .
CLR .
CTS-2-2-1
CTS NET. .
. 4-1 NET.
CTS .
-4-1 CTS
. 1 2 .
. Heap
Stack .
NET.
System.Object
.
"NET. " 3 .
CTS CLR .
.
CLS
.
CLR . 1-1 CLS :
1-1 CLS
17
ValueType
Refrence Type
Type
- C# 09177112161 -
CLS.
Byte,Int16,Int32,Int64,Single,Double,Booleam,char,Decimal,Intptr,String
.
.
Byte 64,Int32Int 16Int,.
CLS.
. #C :
public Class Conversion
}
)public double Metric (double inches
{
; )return (2,54 * inches
}
)public double metric (double miles
{
;)return (miles/0,62
}
{
#C CLS .
Metric metric
. #C VB.NET .
-3-2-1
NET. . EXE
DLL .
XML.
NET. DLL EXE .
5-1 2 IL .
.
18
)Visiblity(Scope
manifest
- NET.
.
.
1 .
manifest CLR .
manifest #C .
IL .
. . JIT
IL .
IL
5-1
. NET.
.
DLL
.
.
. .
.
NET. .
.
. NET.
. DLL
.
Digital signature
19
- C# 09177112161 -
#C .
.
:
: public .
:internal .
. .
.
. 6-1 .
.
-6-1
.
. VB.NET
#C NET. .
CLR .
CLR . .
.
IL
.
#C Linker
(AL.exe (Assembly
. #C .
2005VS.NET
.
-4-2-1 1
20
Private
Shared
- NET.
) ( .
. .
AppBase . .
override
AppBase .
GAC1
. GAC NET. .
.
.
Assembly ) (winnt .
7-1 .
NET. DLL Explorer
Windows GAC .
: .
: .
:
>number>.<minor number>.<build>.<revision
<major
.
AssemblyVersion .
:
AssemblyCulture .
]AssmblyCulture ("fr-CA
[ ("assembly:
: NET.
2
.
/ .
8 .
.
21
Signing
- C# 09177112161 -
-7-1
-4-2-1
IL .
.NET
. .NET . .
. NET Image Generator (Ngen
(Native "
CLR JIT . IL .
.
.
CLR
IL
. .
CLR
. CLR
.
FCL -3-1
FCL ) (
CLR .
.
.NET .
22
Native Image
Code verification
- NET.
FCL .
. System.Drawing
D2System.Drawing.Drawing .
System.IO . .
FCL DLL . .
.1 FCL .
8-1 ILdasm.exe mscorlib .
mscorlib System
.NET System.Collections
.
2-1 .NET .
2-1
System
.
Math .
System.Collections
System.Collections.Specialized
System.Collections.Generic
Stack,HashTable , ArrayList
...
Span
23
- C# 09177112161 -
System.Data
System.Data.OracleClient
System.Data.OleDB
System.Data.Odbc
System.Diagnostics
Oledb,Odbc
).(ADO.NET
Oracle SQLServer
log .
System.Drawing
System.Drawing.Drawing2D
System.Drawing.Printing
System.Drawing.Text
System.Globalization
+GDI .
.
.
System.IO
.
.
System.Net
.
WebRequest WebResponse
.
System.Reflection
System.Reflection.Emit
. Emit IL
.
System.Runtime.InterOpServices
DLL
COM .
System.Security
System.Securing.Permission
System.Securing.CryptoGraphy
System.Text.ReqularExperssions
System.Threading
System.Threading.Thread
System.Web
System.Web.Services
System.Web.UI
System.Web.UI.WebControls
System.WebSecurity
..NET
.
.NET .
.ASP.NET
.
Web.UI
.
24
- NET.
System.Windows.Forms
GUI
ListBox,TextBox,DataGrid,Buttons:
System.XML
XML
FCL.
-1-4-1
.NET
.
.
. .
:
\wint\Microsoft.NET\Framwork\V1,0,3705
\wint\Microsoft.NET\Framwork\V1,1,4322
\wint\Microsoft.NET\Fromwork\V2,0,40607
.
.NET . .
-2-4-1
.NET
.NET .
.
. :
/
25
- C# 09177112161 -
.
3-1 .
.
-3-1 NET.
AL.exe
AssemblyLinker
.
(satellite).
Fuslogrw.exe
Assembly Binding log
Viewer
Gacutil.exe
Global Assembly Cache
Tool
Ildasm.exe
MSSL disassembler
Mscorcfg.msc
NET.Framwork
Configuration Tool
.
.
GAC
GAC .
IL .
MMC .
.
.
.
Ngan.exe
Native Image
Generator
Sn.exe
Strong name tool
Wincv.exe
Windows Forms class
Viewer
Wsdl.exe
IL .
.
.
.
.
SDK:
C:\progerm files\Microsoft.NET\SDK\ V2,0\Bin
path .
:
.1
Computer
My Properties .
26
- NET.
.2
Advanced Variables
Enviroment .
.3 Path SDK .
VS VS .
.
ILdasm.exe
Language Disassembler
. NET. NET.
.
:
C:\ILdasm /adv
adv/ . GUI File
. GAC .
9-1 .
.
1-9 ILDasm.exe
IL .
. metric
Conversion
Metric,conversion, .
.
public class Conversion
{
)public double Metric(double inches
{
;)return(2,5*inches
}
])[CLSCompliantAttribute(false
)public double metric(double miles
{
return
;)(miles/0,62
}
)public double Conversion(double pounds
{
27
- C# 09177112161 -
;)(pounds*454
return
}
}
metric IL . ILdasm
IL . .
ILdasm .
. ILdasm File-Dump .
1
ILdasm
.
. .
. JIT .
IL . 10-1
.
10-1
IL CLR .
.
""a","b .
.
. while if,goto
VS.NET
Wincv.exe
Wincv Viewer
Studio
Object
Visual .
program
.X\Bin1files\Microsoft.NET\V .
. 11-1
obfuscation
28
- NET.
11-1
Wincv .
:
.1 System.Array .
.2
mscorlib.dll . NET.
.3 Array .
.4 .
.
-3-4-1
.
Sanp-in MMC . Control Panel Tools
Framwork Configuration
Adminisrrarive
Microsoft.NET .
: GAC .
: 1 .
CLR .
1,1
1,0 . 1,0
1,1
. .
NET. : NET.
.
.
Binding
29
- C# 09177112161 -
:
.
) . (.
DLL NET. .
:
CLR
.
.
. .
.
.
Configuration Application
an
Fix .
12-1 . .
.
. .
12-1
. 1 .
Trust An Assembly,Adjust .NET Security
Tools
.Application,
Fix an
Framework wizards
Adminisrative .
wizard
30
- NET.
-5-1 C#
NET. VS IDE
.
SDK.
NET #C . NET.
. SDK .
. IDE
.
13-1 .
#C . IDE
.
-13-1
-1-5-1
(CSC.exe
(C# NET. .
C:\winnt\Microsoft.NET\Framework\V2,0,40607
. ) #C
Path ( .
C:\>CSC /help
-2-5-1
Client.cs Client.exe .
C:\>CSC Client.CS
C:\>CSC /t:exe client.CS
. 4-1
:t/
.
t:exe/ .
-4-1 #C
31
- C# 09177112161 -
/addModule
.
.
/debug
/define
define:DEBUG/ .
/delaysign
/doc
.
XML .
/keyfile
snk. .
/lib
refrence/ .
/out
.
exe.
/refrence
/resource
)/target (t
t:exe/ exe . .
t:library/
dll. .
t:module/ .
t:winexe/ exe .
.
#C Client.CS ClientLib.CS .
//Client.CS
; using Sysyem
public class MyApp
{
)static Vold Main (string[ ] args
{
;)"SnowName.ShowMe ( "Core C#
}
}
//Clientlib.CS
; using System
public class ShowName
{
)public static void ShowMe (string MyName
{
;)Console .write line (MyName
}
}
Client Clientlib
. #C .
:1
32
- NET.
#C .
clientlib.CS
client.CS
CSC /out:client.exe
:2
Clientlib .
/t:library Clientlib.CS
CSC
Clientlib.dll . Client .
Client.CS
/r:Clientlib.dll
CSC
Client.exe . ILdasm .
Clientlib.
:3
Clientlib Client.exe
. . Clientlib.CS
. t:Module/ .
Clientlib.CS
/t:module
CSC
Clientlib.NETModule . addModule/
.
Client.CS
/addModule:Clientlib.NETModule
CSC
14-1
-6-1
IL JIT ) (NET.
CLR . .
33
- C# 09177112161 -
CLR .
.
.
FCL
CLR . .
FCL DLL
.
NET.
.
.NET
OpenSource .
34
C #
:
-
:#C #C NET.
.
-
:1 FCL
.
#C : .
:
.
: #C .
.
2000 ECMA #C
. 334ECMA-
++C .
2 .
#C #C .
.
. .
.
Primitive
- C# 09177112161 -
-1-2 #C
1-2 #C .
1-2
Label .
-2 .
. VB #C .
1 . public
Apparel .
-3 )( Main #C . .
static M . overload Main
. .
)(static int Main
{
return ; // must return an integer value
}
.
)static int Main(string[] args
{
// loop through arguments
)foreach (string myArg in args
;)Console.WriteLine(myArg
;return
modifier
36
- #C
}
.
MyApparel .
C:\> MyApparel
: System.Environmenet.CommandLine .
-1-1-2 #C
. class 1-2 Class
.
ECMA #C .
. 1-2
.
-1-2
I .
.
;public const double GramToPound =
EventHandler .
Event EventArgs .
Exception.
I IDisposable .
public Pascal .
.
}public enum WarmColor { Orange, Yellow, Brown
int myIndex
Arshia.GraphicsLib
Pascal Camel .
37
- C# 09177112161 -
:
: Pascal -1 .
:Camel -2 .
#C
#C : Xml ) ( //
) (/* */ .
// for a single line
/* for one or more lines
*/
>/// <remarks> XML comment describing a class </remarks
>:<example
<exception
>"cref="Excep
cref .
>"///<exceptioncref="NoParmException
></exception
<include
>"file="myXML
<param
>"name="parm
<permission
>"" =cref
file xml
.
name .
:
>"///<permissioncref="System.Security.PermissionSet
></permission
> <returns .
> <remarks > <summary .
<seealso
>"cref="price
cref .
export
38
- #C
XML XML
XML . .
ConsoleApp.cs XML ConsoleXML.xml .
C:\> csc consoleapp.cs /doc:consoleXML.xml
1-2 public .
Warning CS: Missing XML comment for publicly visible type ...
1591nowarn:/ .
.
-2-2
.
. #C
.
. 3-2 .
-3-2 #C
#C
FCL
object
System.Object
string
System.String
decimal
System.Decimal
28
bool
System.Boolean
true false
char
System.Char
16
byte
System.Byte
sbyte
System.SByte
short
System.Int16
16
int
System.Int32
32
long
System.Int64
64
ushort
System.UInt16
16
uint
System.UInt32
32
ulong
System.UInt60
64
(single(float
System.Single
double
System.Double
39
- C# 09177112161 -
BCL1 .
:
;)System.Int age = new System.Int(
;int age =
;System.Int age =
IL . #C int 2
32System.Int #C . .
:
-
.
. 32Int
32
.
int iMax = int.MaxValue; // Return largest integer
int pVal = int.Parse(""); // converts string to int
#C .
.
3 . 4
.
.
short i = ; // -bit integer
int i = i; // Okay: int has greater precision
i = i; // Fails: short is bit, int is
i = (short) i; // Okay since casting used
String.
Decimal
decimal 128 . 28
. decimal .
bool
40
decimal
= iRate
decimal
decimal
decimal
// Next
decimal
Alias
Widening conversion
Narroving conversion
literal
- #C
Char
char 16 1 .
char : ) (
.escape System.char
.
Byte , sbyte
uint ulong.
;short i =
i = xC ; // hex value for
int i = i; // no casting required
single double
32 64 . NET.X Single
float.
-
Nan . 0,0
NaN 0,0.
unicode
41
- C# 09177112161 -
System.Convert .
;float xFloat = F
int xInt = Convert.ToInt(xFloat); // returns
;int xInt = (int) xFloat
if(xInt == xInt) { } // False
;)string xStr = Convert.ToString(xFloat
;single zero =
if (Single.IsNaN( / zero)) { } // True
;double xDouble = D
Parse TryParse .
;)"short shParse = Int.Parse("
;)"int iParse = Int.Parse("
;)"long lparse = Int.Parse("
;)"decimal dParse = decimal.Parse("
;)"float sParse = float.Parse("
;)"double dbParse = double.Parse("
. .
-3-2
#C
.
-1-3-2
4-2 .
1 . .
4-2
)(3
;int x = y +
)(2
/
%
)(1
;int x =
++
;int y =
int z = x * y / ; //
y = x % ; // remainder is
;x =
--
~ )( 1
Console.WriteLine(x++) // x =
Console.WriteLine(++x) // x =
int x = ~; // returns -
42
- #C
<< )(4
>>
& )(5
And
| )(6
Or
^ )(7
Xor
byte x = ; // binary is
int result = x << ; // =
result = x >> ; // =
byte x = ; //
byte y = ; //
int result = x & y; // =
result = x ^ y; // =
#C : . ()Math.Power
)( e Math.Exp .
-2-3-2
.
. 5-2
#C .
-5-2
==
!=
>
>=
<
<=
&&
||
}if (x == y) {...
And
Or
false
.
&
|
!
And
Or
.
}if !(x ==y && y < ) {...
- C# 09177112161 -
;string pass
;int grade=
;"If(grade >= ) pass="pass"; else pass="fail
// expression ? op : op
;"pass = (grade >= ) ? "pass" : "fail
true ?! .
-4-2 #C
1 #C .
2 .
# . # .
6-2 #C .
-6-2 #C
#C
define#
undef#
if# true .
if#
if-else #C .
line#
region#
IDE
endregien#
2005VS .
error#
)( .
warning#
#if
#elif
#else
#endif
-1-4-2
if# .
if# endif# if true false
.
. .
#define DEBUG
;using System
public class MyApp
{
44
Directive
Preprocess
- #C
)(public static void Main
{
)#if (DEBUG
;)"Console.WriteLine("Debug Mode
#else
;)"Console.WriteLine("Release Mode
#endif
}
}
define# cs. . :
. DEBUG (if(DEBUG# true .
define# Debug . 2005VS
Debug DEBUG .
define# .
#C Define/ .
csc /Define:DEBUG myproject.cs
Define DEBUG# .
-2-4-2
. warning# error# .
#define CLIENT
#define DEBUG
;using System
public class MyApp
{
)(public static void Main
{
#if DEBUG && INHOUSE
#warning Debug is on.
#elif DEBUG && CLIENT
#error Debug not allowed in Client Code.
#endif
// Rest of program follows here
CLIENT DEBUGE .
. #C
VS.NET .
#region
// any C# statements
#endregion
-5-2
#C enum 1
.
:
Structured
45
- C# 09177112161 -
}[access modifiers]enum <identifier> [:enum-base]{enum body
:
{ enum Fabric :short
Cotton = ,
Silk = ,
Wool = ,
Rayon = ,
Other =
}
: enum 0123
..... .
enum . internal
. public .
enum-base .
long unit int ushort short sbyte byte ulong . int.
-1-5-2
. .
enum .
. 2-2 Fabric .
2-2
)static double GetPrice(Fabric fab
{
)switch(fab
{
;)case Fabric.Cotton: return(
;)case Fabric.Silk: return(
;)case Fabric.Wool: return(
;)case Fabric.Rayon: return(
;)case Fabric.Other: return(
;)default: return(
}
}
)(static void Main
{
;Fabric fab = Fabric.Cotton
int fabNum = (int) fab; //
"string fabType = fab.ToString(); // "Cotton
"string fabVal = fab.ToString("D"); // "
double cost = GetPrice(fab); //
}
enum .
()ToString D .
Fabric GetPrice
46
- #C
.
System.Enum
foreach .
-2-5-2 System.Enum
Enum.IsDefinedEnum.Parse Enum.Getname System.Enum .
enum .
. Fabric
GetName .
;"string fabStr = "Cotton
// Determine if symbol Cotton exists in Fabric enum
))if (Enum.IsDefined(typeof(Fabric),fabStr
{
// Create enum instance
;)Fabric fab = (Fabric)Enum.Parse( typeof(Fabric) , fabStr
"// Output from the following statement is: "Silk
;))Console.WriteLine("Second value of Fabric Enum is: " + Enum.GetName(typeof(Fabric),
}
ISDefined : typeof
. .
Parse IsDefined . fab
2-2 . enum Parse
.
GetName enum . Silk
2.
-3-5-2 flag
Fabric 2 .
. .
.
;Fabric cotWool = Fabric.Cotton | Fabric.Wool
Console.WriteLine(cotWool.ToString()); // Output:
Wool Cotton .
] [flags .
][Flags
{ enum Fabric :short
()ToString .
. 5
()ToString 101 001 100 .
cotton,wool.
47
- C# 09177112161 -
-6-2
CLR : ) .(2-2
. byte char int
enum struct . NET.
.
-2-2 NET.
-2-6-2
ClR .
Stack Heap
Stack .
3-2
.
;)(Apparel myApparel = new Apparel
;Apparel myApparel = myApparel
48
- #C
-2-3
CLR -1 Heap .
-2 Heap .
SyncBlockIndex .
-3 myApparel Apparel Price FabType
Heap .
-4 myAparel Stack .
-5 2myApparel Stack
. myApparel 2myApparel .
.
.
.
-3-6-2
.NET Object .
. Object
Heap . :
;int age =
;object refAge = age
. "
"2 .
.
;int newAge = (int) refAge
string newAge = (string) refAge; // Fails. InvalidCastException
49
Boxing
Unboxing
- C# 09177112161 -
.
ClR .
. System.Array ArrayList .
.
Arraylist Object . ArrayList
.
. .
ArrayList .
ArrayList . 4-2
.
// Create array with four values
;}int[] ages = {
// Place four values in ArrayList
;)(ArrayList ages = new ArrayList
)for (int i=; i<; i++
{
ages.add(i); // expects object parameter
}
int ArrayList . .
.
ArrayList . 2,0NET .
List ArrayList .
: Stack .
GC Heap GC . NET.
.
-7-2
.
.
.
.
.
50
- #C
namespace CustomerPhoneBookApp
{
;using System
public struct Subscriber
{
// Code for struct here...
}
}
Subscriber
CustomerPhoneBookApp.Subsciber .
.
.
namespace Arshia
{
namespace ProCSharp
{
namespace Basics
{
class NamespaceExample
{
// Code for the class here...
}
}
}
}
.
.
Arshia.ProCSharp ProCSharp NamespaceExample
Arshia.ProCSharp.Basics.NameSpaceExample.
.
.
namespace Arshia.ProCSharp.Basics
{
class NamespaceExample
{
// Code for the class here...
}
}
: .
.
.
-1-7-2 using
#C .
using .
.
;using System
;using Arshia.ProCSharp
51
- C# 09177112161 -
#C using System .
System .
using
.
NamesspaceExample Arshia.ProCSharp.Basic Arshia.ProCSharp.OOP .
Test Arshia.ProCSharp
NameSpaceExample .
;using Arshia.ProCSharp
class Test
{
)(public static int Main
{
;)(Basics.NamespaceExample nSEx = new Basics.NamespaceExample
// do something with the nSEx variable
;return
}
}
-2-7-2
using .
. using
.
;using alias = NamespaceName
Introduction Arshia.ProCSharp.Basic
NamespaceExample . 1 ) (:: .
. Introduction
. :: .
NamespaceExample ()GetNamespace ()GetType . GetType
Type .
.
;using System
;using Introduction = Arshia.ProCSharp.Basics
class Test
{
)(public static int Main
{
= Introduction::NamespaceExample NSEx
;)(new Introduction::NamespaceExample
;))(Console.WriteLine(NSEx.GetNamespace
;return
}
}
Qualifier
52
- #C
namespace Arshia.ProCSharp.Basics
{
class NamespaceExample
{
)(public string GetNamespace
{
;return this.GetType().Namespace
}
}
}
-8-2 I/O
#C . Console
#C .
1
()Console.ReadLine .
. .
)(Console.Write
.
)(Console.WriteLine
.
.
. .
;)(string s = Console.ReadLine
;)Console.WriteLine(s
()Console.WriteLine printf C
. WriteLine .
. }{ .
. } {0
. .
;int i =
;int j =
;)Console.WriteLine("{} plus {} equals {}", i, j, i + j
.
10 plus 20 equals 30
.
. } {n,w n w .
;int i =
;int j =
;)Console.WriteLine(" {}\n+{}\n ----\n {}", i, j, i + j
+
----
Stream
53
- C# 09177112161 -
)( .
:
. 10
.
)( . ) 6
( . ) e (E .
. . .
. f e .
)( . 32076744
. .
e/E .
. 2C
.
;decimal i = m
;decimal j = m
;)Console.WriteLine(" {:C}\n+{:C}\n ---------\n {:C}", i,j, i + j
.
$
$
--------$
.
:
;double d =
;)Console.WriteLine("{:#.}", d
23. . #
.
-9-2
#C.
#C ....
#C .
54
- #C
()Main #C.
#C .
#C Pascal
Camel .
#C /// /* */ // .
#C FCL.
TryParse Parse....
#C C.
& | .
.
#C .
def# undef# .
2
.
. Stack
Heap .
System.ValueType System.Object .
object .
object .
.
.
. using
.
:: .
55
)(continue break
.
.
.
1
: 2 .3
. .
.
.
. .
#C . .if, else, switch
.
.
") .
Branching
unconditional
Conditional
#C
-1-3
.
. .
. :
UpdateSalary ( ) ; // invokes the method up date salary
. .
1-3 .
-1-3
1-3 . 1-3
()Main . . ()1Method
. ()1Method .
()A1Method . ()A1Method.
()A1Method ()A1Method .
()1Method . ()1Method .
()Main . ()2Method . ()2Method
()Main . ()Main .
1-3 . ()Main
()SomeMethod . ()WriteLine
.
1-3
57
2006
f/
;using System
class Functions
{
(static void Main
-
{
;) ")...
}
) (static void SomeMethod
{
;) "!Console.WriteLine( "Greetings from SomeMethod
}
}
:
)...
()Main ()SomeMethod ) .
( . .
.
goto
return throw . .
break, continue,
-2-3
.
" 25 " .
#C .
.
-1-2-3 if
if . if :
. . .
true false .
if :
) ( if
1
if . if
true 1 . 1
}{ ) . 2-3 (.
2-3
;using System
namespace Branching
{
class Test
{
58
#C
static void Main(
{
int valueOne = 10;
int valueTwo = 20;
int valueThree = 30;
Console.WriteLine( "Testing valueOne against valueTwo..." );
if ( valueOne > valueTwo )
{
Console.WriteLine( "ValueOne: {0} larger than ValueTwo: {1}",valueOne,
valueTwo );
}
Console.WriteLine( "Testing valueThree against valueTwo..." );
if ( valueThree > valueTwo )
{
Console.WriteLine( "ValueThree: {0} larger than ValueTwo: {1}",
valueThree, valueTwo );
}
// end if
}
// end Main
}
// end class
}
// end namespace
{} #C
.
. 30 20 10 valueOne,valueTwo,valueThree
:valueTwo valueOne if
if (ValueOne>ValueTwo)
{
Console Write Line("Value One:{0}Laser then Value Two: {1}"
ValueOne , ValueTwo);
}
if -2-2-3
) 2-3 if
2-3 . if .(()WriteLine
. 3-3
59
-
using System;
namespace Branching
{
class Test
{
static void Main( )
{
int valueOne = 10;
int valueTwo = 20;
}
}
: . if
.
.
.
if .
3 valueThree . 4-3 .
. if
4-3
using System;
namespace Branching
{
class Test
{
static void Main( )
{
int valueOne = 10;
int valueTwo = 20;
}
}
60
#C
.
.
.
Testing Value One against Value Two
Testing Value Three against Value Two
Good thing you tested again
.
. ) " (" Good thing ... if.
) if ( valueThree > valueTwo
Console.WriteLine( "ValueThree: {0} larger than ValueTwo: {1}",
;)valueThree, valueTwo
;)"!Console.WriteLine("Good thing you tested again
if . if .
if .
) if ( valueThree > valueTwo
Console.WriteLine(ValueThree: {0} larger than ValueTwo:{1}", valueThree,
;)valueTwo
;)"!Console.WriteLine("Good thing you tested again
if .
) if ( valueThree > valueTwo
{
Console.WriteLine( "ValueThree: {0} larger than ValueTwo: {1}",
;)valueThree, valueTwo
;)"!Console.WriteLine("Good thing you tested again
#C if if
.
if
.
)if (condition
{
// statement
}
)if (condition
{
// statement
}
{)if (condition
// statement
}
61
if if
. . .
if if . K&R ).
(Kernighan ,Ritchie C .
. K&R
.
-3-2-3
:
int
;x=8
int
;y= 15
if . if true
if true . (8x==) : )== (12y
(||) or . x 8 )== (8x true
)== (12y y 12 true .
:
;x=8
int
int
;y=12
20 .
. if false
. .
)public bool QuotientOverTwenty(float dividend, float divisor
{
;bool retVal = false
62
#C
) if ( divisor != 0
{
) if ( dividend / divisor > 20
;retVal = true
}
;return retVal
}
:
Testing valueOne against valueTwo...
Nope, ValueOne: 10 is NOT larger than ValueTwo: 20
if if else
if else .
63
-5-2-3 if
if .
:
-
32 .
32 .
32 .
. 6-3 if
.
6-3
;using System
class Values
{
(static void Main
{
;int temp = 32
) if ( temp <= 32
{
;) "!Console.WriteLine( "Warning! Ice on road
) if ( temp == 32
{
;) "Console.WriteLine("Temp exactly freezing, beware of water.
}
else
{
;) Console.WriteLine( "Watch for black ice! Temp: {0}", temp
}
}
}
}
6-3 : 32 . :
)if ( temp<=32
;)" Console. Write line ( " warning Ice on road
32 32
.
if if . else " :
32 32 32".
if else if #C .
if . false else if
. 6-3
. 7-3 .
7-3
;using System
class Values
64
#C
{
)
) if ( temp < 32
{
;) "!Console.WriteLine( "Warning! Ice on road
}
) else if ( temp == 32
{
;) "Console.WriteLine("Temp exactly freezing, beware of water.
}
else
{
;) Console.WriteLine( "Watch for black ice! Temp: {0}", temp
}
}
}
if 32 32 . false
else if . if true ) (else
. :
;using System
class Values
{
(static void Main
{
;int temp = 32
) if ( temp < 32
{
;) "!Console.WriteLine( "Warning! Ice on road
}
else
{
) if ( temp == 32
{
;) "Console.WriteLine("Temp exactly freezing, beware of water.
}
else
{
;) Console.WriteLine( "Watch for black ice! Temp: {0}", temp
}
}
}
}
else if else if else
-6-2-3 switch
if .
switch . switch " :
"
) switch ( expression
{
65
-
case constant- expression
Statement
Jump- Statement
][ default: statement 1
}
switch . case
. .
case .
case . case
. break switch switch
.
8-3 .
.
8-3
class Values
{
enum Party
{
Democrat,
Republican,
Progressive
}
)(static void Main
{
// hard wire to Democratic
;Party myChoice = Party.Democrat
// switch on the value of myChoice
) switch ( myChoice
{
case Party.Democrat:
;) "Console.WriteLine( "You voted Democratic.
;break
case Party.Republican:
;) "Console.WriteLine( "You voted Republican.
;break
case Party.Progressive:
;) "Console.WriteLine( "You voted Progressive.
;break
}
;) "Console.WriteLine( "Thank you for voting.
}
}
:
You voted Democratic.
Thank you for voting
8-3 if switch .
switch case ) .
.(Democrat
case break .
. case break .
66
#C
case 9-3
..
9-3
using System;
class Values
{
enum Party
{
Democrat,
Republican,
Progressive
}
static void Main()
{
// hard wire to Democratic
Party myChoice = Party.Democrat;
// switch on the value of myChoice
switch ( myChoice )
{
case Party.Democrat:
Console.WriteLine( "You voted Democratic." );
break;
case Party.Republican:
Console.WriteLine( "You voted Republican." );
break;
case Party.Progressive:
Console.WriteLine( "You voted Progressive." );
break;
default:
Console.WriteLine( "You did not make a valid choice." );
break;
}
Console.WriteLine( "Thank you for voting." );
}
}
:
You did not make a valid choice.
Thank you for voting.
. default case
.
. while
case -7-2-3
case " 1 " case case
: .
case Compassionate Republican :
case Republican :
Console.WriteLine( "you voted Republican./n");
Console.Write line( "do not you feel compassioned");
Falling
through
67
case . case
. case . case
case . goto case .
goto .
. .
NewLeft . NewLeft
Democrat . :
case NewLeft:
;)"Console. write line("the New Left members are Voting Democratic
case Democrat :
;)"Console. write line(" you Voted Democratic./n
;Break
:
Control cannot fall through from one case label(case'4') To another
.
. case ) (4
) (NewLeft . NewLeft .
int
const
;Democrat = 0
const
int
const
;int Progressive = 3
const
;Republican = 2
;int NewLeft = 4
const
. Democrat NewLeft
.
-8-2-3 switch
switch #C . switch .
10-3 9-3 switch
10-3
;using System
class Values
{
) (static void Main
{
;"String myChoice = "NewLeft
// switch on the string value of myChoice
) switch ( myChoice
68
#C
{
case "NewLeft":
(Console.WriteLine
;) ""The NewLeft members are voting Democratic.
;"goto case "Democrat
case "Democrat":
;) "Console.WriteLine( "You voted Democratic.\n
;break
case "CompassionateRepublican": // fall through
case "Republican":
;) "Console.WriteLine( "You voted Republican.\n
;) "?Console.WriteLine( "don't you feel compassionate
;break
case "Progressive":
;) "Console.WriteLine( "You voted Progressive.\n
;break
default:
;) "Console.WriteLine( "You did not make a valid choice.
;break
}
;) "Console.WriteLine( "Thank you for voting.
}
-3-3
. . ) (
.
.
.
.
#C for, while, do while foreach .
goto . goto, for, while, do
while .
-1-3-3 goto
goto switch .
goto . goto .
goto .
. goto .
switch . goto :
-1 -2 goto
69
-
goto .
if goto 11-3 .
.
11-3
using System;
public class Tester
{
public static void Main( )
{
int counterVariable = 0;
repeat: // the label
Console.WriteLine(
"counterVariable: {0}", counterVariable );
// increment the counter
counterVariable++;
if ( counterVariable < 10 )
goto repeat; // the dastardly deed
:
counterVariable: 0
counterVariable: 1
counterVariable: 2
counterVariable: 3
counterVariable: 4
counterVariable: 5
counterVariable: 6
counterVariable: 7
counterVariable: 8
counterVariable: 9
. goto .
. goto
while 5-3-2
70
#C
) while ( counterVariable < 10
{
;) Console.WriteLine( "counterVariable: {0}", counterVariable
;counterVariable++
}
}
:
counterVariable: 0
counterVariable: 1
counterVariable: 2
counterVariable: 3
counterVariable: 4
counterVariable: 5
counterVariable: 6
counterVariable: 7
counterVariable: 8
counterVariable: 9
-3-3-3 do while
while . while
71
-
// display the message and then test that the value is
// less than 10
do
{
;) Console.WriteLine( "counterVariable: {0}", counterVariable
;counterVariable++
;) } while ( counterVariable < 10
}
}
:
counter variable : 11
-4-3-3 for
while 12-3 .
) .(counterVariable ) .(counterVariable <10 for
. for for
:
);]for([initializes];[BooleanExpression];[iterates
Statement
.
. .
. for 14-3 .
14-3
;using System
public class Tester
{
) (public static void Main
{
) for ( int counter = 0; counter < 10; counter++
{
(Console.WriteLine
;) "counter: {0} ", counter
}
}
}
:
counter: 0
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 6
72
#C
counter: 7
counter: 8
counter: 9
counter . counter
. counter .
.
. counter 10 . for
. counter . counter
. true for .
++ . . for
++counter counter ++ .
for " counter true
counter "
) for( break
for . for
break .
break for for . 16-3
.
16-3
;using System
public class Tester
{
) (public static void Main
{
) for ( int counter = 0; counter < 10; counter++
{
;) Console.WriteLine( "counter: {0} ", counter
// if condition is met, break out.
) if ( counter == 5
{
{
;) "Console.WriteLine( "Breaking out of the loop
;break
}
}
;) "Console.WriteLine( "for loop ended
}
}
}
:
counter: 0
counter: 1
counter: 2
counter: 3
73
-
counter: 4
counter: 5
Breaking out of the loop
for loop ended
5 5 for
.
continue
"
continue .
.
continue break
.
. continue break 17-3
.
17-3
using System;
public class Tester
{
public static int Main( )
{
string signal = "0"; // initialize to neutral
while ( signal != "X" ) // X indicates stop
{
Console.Write( "Enter a signal. X = stop. A = Abort: " );
signal = Console.ReadLine( );
// do some work here, no matter what signal you
// receive
Console.WriteLine( "Received: {0}", signal );
if ( signal == "A" )
{
// faulty - abort signal processing
// Log the problem and abort.
Console.WriteLine( "Fault! Abort\n" );
break;
}
if ( signal == "0" )
{
// normal traffic condition
// log and continue on
Console.WriteLine( "All is well.\n" );
continue;
}
// Problem. Take action and then log the problem
// and then continue on
Console.WriteLine( "{0} -- raise alarm!\n", signal );
}
return 0;
}
}
74
#C
.
()Console.ReadLine . A .
" ) "0( .
) Abort " "A ( .
. " "X while .
:
Enter a signal. X = stop. A = Abort: 0
Received: 0
All is well.
Enter a signal. X = stop. A = Abort: 1
Received: 1
!1 -- raise alarm
Enter a signal. X = stop. A = Abort: X
Received: X
!X -- raise alarm
:
Enter a signal. X = stop. A = Abort: A
Received: A
Fault! Abort
A . if
. 0 . .
X A .
for
for
:
)]for([Initializes];[BooleanExpression]; [Aerators
Statement
for . 18-3
for .
18-3
;using System
public class Tester
{
) (public static void Main
{
;int counter = 0
// some work here
;counter = 3
// more work here
) for ( ; counter < 10; counter++
{
;) Console.WriteLine("counter: {0} ", counter
}
}
}
75
:
counter: 3
counter: 4
counter: 5
counter: 6
counter: 7
counter: 8
counter: 9
counter for . ;
.
counter for . -3
19 .
19-3
;using System
public class Tester
{
) (public static void Main
{
for ( int counter = 0; counter < 10; ) // no increment
{
;) Console.WriteLine( "counter: {0} ", counter
// do more work here
counter++; // increment counter
}
}
}
for :
) ;for ( ; counter< 10
while for . for
:
) ; ; ( for
76
#C
;break
}
}
}
:
counter: 0
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 6
counter: 7
counter: 8
counter: 9
10counter:
.
.
-4-3
.
.
.
.
true if .
if or . true
. .
if .
switch
.
switch default
.
.
.
77
goto .
while true .
.
dowhile while .
.
for . for
. for
.
.
78
1 2 .... .
3 .
4 .
. .
.
) ( 5
. .
... .
.
.
....
.
PopUp
Listbox
Interface
problem domain
- C# 09177112161 -
1 .
. .
. .
... .
. .
.
. .
2 .
-1-4
.
. . . .
3 .
.
.
.
.
-2-4
.
. .
.
. .
80
object state
Encapsulation
simplification
.
. #C 1
2 .
.
.
Car . Car . Car.
. Car .
.
:-3-4 :
. #C 3
.
class Dog
{
private int weight; // member field
private String name; // member field
. Dog .
.
. .
class Dog
{
;private int weight
;private String name
public void Bark( ) // member method
{
// code here to bark
}
private public .
private public
.
81
class
instance
Member field
- C# 09177112161 -
. Dog 1
2 ... . .
.
. .
) . ()Feed ( . ) Bark
( Sniff ) .(BegForFeed .
.
) ( .
-4-3 :
. .
. Manager
UpdateSalary . Manager Employee
3 . .
. ...
. .
.
. Has-a .
. . Is-a.
.
NET. String . Address
. Employee Address.
-5-4
: .
. .
82
Bark
nap
associate
.
.
-1-5-4
.
) (self-contain .
.
.
.
public .
.
.
.
public .
()NetPresentValue
. .
-2-5-4
1 #C 2 )
( . .
3 . .
Is-a . . )
(.
Manager Employee . ) ( )
( Manager . . Manager
Manager .
. Button ListBox . .
) ( ) (... .
. paste, cut
.
specialization
inheritance
Derived
83
- C# 09177112161 -
-3-5-4
poly . morph
. .
.
) . (ListBox Button
. .
Draw
. .
.
-6-4
.
. .
.
. use-case
.
.
.
. .
.
.
-7-4
84
.
.
. .
85
this
) (#c .
. #c
. . #c
.
.
.
.
. .
.
.
.
ListBox . ListBox
. .
. ListBox
. . .
#C .
. .
. Dog Bark ListBox
Sort .
. .
.
.
-1-5
.
. ListBox
ListBox .
.
1 . .
ListBox
.
.
class . .
}[attributes ] [access-modifiers] class identifier [:base-class] {class-body
2 ) ( .
#C . )
public (.
3 . #C ) ( .
.
).(GoldenRetriever
. .
. .
class Dog
{
int age; // the dog's age
int weight; // the dog's weight
} Bark( ) { //...
87
listBox
Attributes
identifier
- C# 09177112161 -
} Eat( ) { // ...
}
Dog .
.
-1-1-5 1
.
.
.
Dog milo; // declare milo to be an instance of Dog
. Camel .
myDog.
.
new .
milo=new Dog();//allocate memory for milo
.
;() Dog milo=new Dog
milo Dog Dog .
.
#C . . ()Main
.
()Main ()Main .
public class Tester
{
) (public static void Main
{
//...
}
}
Instantiate
88
-2-1-5 Time
.
. .
NET. DataTime .
6 ) (1-5 .
1-5 Time
;using System
public class Time
{
// private variables
;private int year
;private int month
;private int date
;private int hour
;private int minute
;private int second
// public methods
) (public void DisplayCurrentTime
{
;) "Console.WriteLine( "stub for DisplayCurrentTime
}
}
public class Tester
{
) (static void Main
{
;) (Time timeObject = new Time
;) (timeObject.DisplayCurrentTime
}
}
#C ) ( .
.
89
- C# 09177112161 -
. DisplayCurrentTime
.
Time Tester ()Main . ()Main Time
timeObject .
;) (Time timeObject = new Time
) (
. .
-3-1-5
. 1-6
#C .
-1-5
public
. public
.
private
protected
internal
Protected
Internal
public
.
.
private
public
.
.
Restrictions
90
:
.
Time ()DisplayCurrentTime public .
private . 2-6
()DisplayCurrentTime Tester .
Time DisplayCurrentTime public .
-2-5
. .
.
ListBox ()Sort
.
. .
. ()MyMethod void
.
)void MyMethod (int firstParam, Button secondParam
{
// ...
}
. 2-5 .
2-5
;using System
public class MyClass
{
) public void SomeMethod( int firstParam, float secondParam
{
Console.WriteLine("Here are the parameters received: {}, {}",firstParam,
;) secondParam
}
}
public class Tester
{
) (static void Main
{
;int howManyPeople =
;float pi = f
;) (MyClass mc = new MyClass
;) mc.SomeMethod( howManyPeople, pi
}
}
:
Here are the parameters received 53,14
) (Main howManyPeople pi .
SomeMethod . howManyPeople firstParam pi
secondParam .
91
- C# 09177112161 -
-3-5
1-6 Time ()Time.
;) (Time timeObject = new Time
.
. .
.
.
2-5 Time .
.
. .
. 2-5
.
2-5
bool
flase
char
null \0
Enum
Refrence
null
. 3-5 .
:
-1 .
-2 .
. 3-5
Time 6 .
3-5
;using System
public class Time
{
// private member variables
;int year
;int month
;int date
;int hour
92
hour,
year,
;int minute
;int second
// public method
) (public void DisplayCurrentTime
{
}System.Console.WriteLine( "{}/{}/{
}
// constructor
public Time( int theYear, int theMonth, int theDate,int theHour, int theMinute,
) int theSecond
{
;year = theYear
;month = theMonth
;date = theDate
;hour = theHour
;minute = theMinute
;second = theSecond
}
}
public class Tester
{
) (static void Main
{
;) Time timeObject = new Time( , , , , ,
;) (timeObject.DisplayCurrentTime
}
}
:
9:35:20 2008/1/8
.
Time .
()DisplayCurrentTime ()Main .
.
.
-4-5
.
.
Private int second =30 ; //intializer
Time 30 . Time
Second . 4-5 .
4-5
;using System
public class Time
{
// private member variables
Initializers
93
- C# 09177112161 -
;int year
;int month
;int date
;int hour
;int minute
;int second =
// public method
) (public void DisplayCurrentTime
{
System.Console.WriteLine( "{}/{}/{} {}:{}:{}",month, date, year, hour,
;) minute, second
}
// constructor
) public Time( int theYear, int theMonth, int theDate,int theHour, int theMinute
{
;year = theYear
;month = theMonth
;date = theDate
;hour = theHour
;minute = theMinute
}
}
public class Tester
{
) (static void Main
{
;) Time timeObject = new Time( , , , ,
;) (timeObject.DisplayCurrentTime
}
}
9:35:30 2008/1/8
.
Second 30 .
. Second
30
.
-5-5 this
this . this
) ( . this :
.
)public void SomeMethod (int hour
{
;this.hour = hour
}
SomeMethod . this
this.hour . hour .
this .
94
-
)public void SetTime(year, month, date, newHour, newMinute, newSecond
{
this.year = year; // use of "this" required
this.month = month; // required
this.date = date; // required
this.hour = hour; // use of "this" optional
this.minute = newMinute; // optional
second = newSecond; // also ok
}
this
.
this . :
Class SomeClass
{
)public void FirstMethod(OtherClass otherObject
{
;)otherObject.SecondMethod(this
}
// ...
}
-6-5
1 2 .
. static
.
. .
.
. Button
btnUpdate bthDelete .
Button ()Draw ()GetButtonCount . ()Draw
GetButtonCount .
.
;) (btnUpdate.SomeMethod
.
;) (Button.GetButtonCount
95
Instance
Static
- C# 09177112161 -
-1-6-5
. this
.
. ()Main
. ()Main .
2005vs StaticTester VS.NET .
StaticTester 1Class 1Class . Tester
] [STATThread VS NET ()Main . args
()Main . :
;using System
namespace StaticTester
{
class Tester
{
) (static void Main
{
}
}
}
. ()Main ()Run
. ()Run .
()Run . Run public
.
) (public void Run
()Run . .
" "Hello world .
) (public void Run
{
;)"Console.WriteLine("Hello world
}
1-5
96
new 1 .
( )Run t Tester . t
Tester .
5-5 .
5-5
;using System
namespace StaticTester
{
// create the class
class Tester
{
// Run is an instance method
) (public void Run
{
;) "Console.WriteLine( "Hello world
}
// Main is static
) (static void Main
{
// create an instance
;) (Tester t = new Tester
// invoke the instance method
;) (t.Run
}
}
}
:
Hello world
. ()Main
()Run .
Intellisense
97
09177112161 - - C#
-2-6-5
.
. Cat
. 6-5 . Cat
6-5
using System;
namespace Test
{
// declare a Cat class
// stripped down
public class Cat
{
// a private static member to keep
// track of how many Cat objects have
// been created
private static int instances = ;
private int weight;
private String name;
// cat constructor
// increments the count of Cats
public Cat( String name, int weight )
{
instances++;
this.name = name;
this.weight = weight;
}
// Static method to retrieve
// the current number of Cats
public static void HowManyCats( )
{
Console.WriteLine( "{} cats adopted", instances );
}
public void TellWeight( )
{
Console.WriteLine( "{} is {} pounds", name, weight );
}
}
class Tester
{
public void Run( )
{
Cat.HowManyCats( );
Cat frisky = new Cat( "Frisky", );
frisky.TellWeight( );
Cat.HowManyCats( );
Cat whiskers = new Cat( "Whisky", );
whiskers.TellWeight( );
Cat.HowManyCats( );
}
static void Main( )
{
Tester t = new Tester( );
t.Run( );
}
}
}
:
98
-
adopted
is pounds
adopted
is pounds
adopted
cats
Frisky
cats
Whisky
cats
Cat instances .
Cat . .
Cat .name , weight : Cat
.
Cat ()TellWeight() ,HowManyCats . ()HowManyCats .
. . ()TellWeight
. ( )Main Cat HowManyCats .
;) (Cat.HowManyCats
Cat ()HowManyCats . .
-7-5
#C (++c,c ( .
1
. )
(.
.
.
#C .
{ } MyClass
.
)(protected override void Finalize
{
try
{
// do work here
}
finally
{
;)(base.Finalize
}
}
Scarce
99
- C# 09177112161 -
1 . .
.
IDisposable . Dispose
.
()Dispose .
()GC.SuppressFinalize this
. ()Dispose :
;using System
class Testing : IDisposable
{
;bool is_disposed = false
) protected virtual void Dispose( bool disposing
{
!if ( !is_disposed ) // only dispose once
{
) if ( disposing
{
Console.WriteLine( "Not in destructor,
;) "OK to reference other objects
}
// perform cleanup for this object
;) "Console.WriteLine( "Disposing...
}
;this.is_disposed = true
}
) (public void Dispose
{
;) Dispose( true
// tell the GC not to finalize
;) GC.SuppressFinalize( this
}
) (~Testing
{
;) Dispose( false
;) "Console.WriteLine( "In destructor.
}
}
()Close . ()Dispose
()Close ()Close ()Dispose .
()Dispose #C using
()Dispose .
. ()Dispose
. :
;using System.Drawing
class Tester
{
) (public static void Main
{
))using (Font theFont = new Font("Arial", f
{
// use the font
}
Finalizer
100
-
}
}
Font .
Font using . using ()Dispose
()Font .
-8-5
. .
.
.
int Stack .
Stack .
Stack .
.
) ( .
.
#C . Stack .
) (long , int Stack .
. Heap .
.
. :
;( )Dog milo=new Dog
new Dog Heap . milo
. milo Dog Heap .
. milo ) Dog ( Heap . milo
. milo Dog .
.
7-5 . .
7-5
;using System
namespace heap
{
public class Dog
{
;public int weight
}
class Tester
{
) (public void Run
{
// create an integer
101
09177112161 - - C#
int firstInt = ;
// create a second integer
int secondInt = firstInt;
// display the two integers
Console.WriteLine( "firstInt: {} secondInt: {}",firstInt, secondInt );
// modify the second integer
secondInt = ;
// display the two integers
Console.WriteLine( "firstInt: {} secondInt: {}",firstInt, secondInt );
// create a dog
Dog milo = new Dog( );
// assign a value to weight
milo.weight = ;
// create a second reference to the dog
Dog fido = milo;
// display their values
Console.WriteLine( "Milo: {}, fido: {}",milo.weight, fido.weight );
// assign a new weight to the second reference
fido.weight = ;
// display the two values
Console.WriteLine( "Milo: {}, fido: {}",milo.weight, fido.weight );
}
static void Main( )
{
Tester t = new Tester( );
t.Run( );
}
}
}
:
firstInt: secondInt:
firstInt: secondInt:
Milo: , fido:
Milo: , fido:
secondInt . 5 firstInt
: . firstInt
firstInt: secondInt:
2-5
firstInt int .
. secondInt 2-5 . secondInt
. secondInt
secondInt = ;
.
.
3-5
102
.
firstInt: secondInt:
5 milo .
;milo.weight =
Dog milo .
heap .
;Dog fido = milo
secondInt
;int secondInt = firstInt
;Dog fido = milo
milo .
Milo : 7, Fido : 7
fido milo . Heap . milo
103
- C# 09177112161 -
Heap
5-5
1 .
-9-5
class 2
.
. new
Heap .
.
.
public .
private .
protected .
.
. .
. this
.
this .
104
Struct
Delegate
.
static . this
.
#C .NET GC .
()Dispose .
Stack .
.
Heap .
Heap .
. Heap
GC .
105
override
, , 1 .
#C .
2 .
-1-6
. ,
is-a .
4 .
.
.
Specialization
Polumorphism
Generalization
characteristic
, . .
, ,
.
.
. . ,
.
Listbox,Button
. , , ListBox,Button
.
,UML UML . 1
. .
,UML 1-6 .
. , Button ListBox Window .
-1-6
.
, . ,
.
: ) (2-6 . RadioButton ,CheckBox ,
CommandButton
Button
) .(3-6 .
Visual
107
#C
-2-6
-3-6
UML 3-6 ListBox Button
Window Button Command CheckBox . RadioButton ,
CheckBox .
.
-2-6
,#c .
. ListBox , Window
, window .
Window 1 ListBox ListBox
Window . , 2
, 3 ) (object .
108
Base class
Parent
Child
-1-2-6
#c
.
public class ListBox : Window
109
#C
{
// create a base instance
;) Window w = new Window( ,
;) (w.DrawWindow
// create a derived instance
;) "ListBox lb = new ListBox( , , "Hello world
;) (lb.DrawWindow
}
}
:
Drawing Window at ,
Drawing Window at ,
Writing string to the listbox: Hello world
-2-2-6
1-6 ListBox Window .
,ListBox ) (:
base .
public ListBox( int theTop, int theLeft, string theContents):
base(theTop, theLeft) // call base constructor
,
. ,
.
. , ,
. ,base .
-3-2-6
public private
protected .
.
, . MyClass :
public class MyClass
{
// ...
;protected int myValue
}
110
: .
.
-3-6
: . ListBox
. .
. .
.
.
.
. .
-1-3-6
ListBox Window Button Window
.
.
. .
.
:
-1 .
-2 override.
virtual .
()Drawwindow 1-6 . virtual
.
) (public virtual void DrawWindow
()DrawWindow
()DrawWindow . ()DrawWindow override .
override .
override override override
. 2-6 override .
-2-6
;using System
public class Window
{
// constructor takes two integers to
111
#C
// fix location on the console
public Window( int top, int left )
{
this.top = top;
this.left = left;
}
// simulates drawing the window
public virtual void DrawWindow( )
{
Console.WriteLine( "Window: drawing Window at {}, {}",top, left );
}
// these members are protected and thus visible
// to derived class methods. We'll examine this
// later in the chapter. (Typically, these would be private
// and wrapped in protected properties, but the current approach
// keeps the example simpler.)
protected int top;
protected int left;
} // end Window
// ListBox derives from Window
public class ListBox : Window
{
// constructor adds a parameter
// and calls the base constructor
public ListBox(int top,int left,string contents ) : base( top, left )
{
listBoxContents = contents;
}
// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow( )
{
base.DrawWindow( ); // invoke the base method
Console.WriteLine( "Writing string to the listbox: {}",listBoxContents );
}
private string listBoxContents; // new member variable
} // end ListBox
public class Button : Window
{
public Button(
int top,
int left ) : base( top, left )
{}
// an overridden version (note keyword) because in the
// derived method we change the behavior
public override void DrawWindow( )
{
Console.WriteLine( "Drawing a button at {}, {}\n",top, left );
}
} // end Button
public class Tester
{
static void Main( )
{
Window win = new Window( , );
ListBox lb = new ListBox( , , "Stand alone list box" );
Button b = new Button( , );
win.DrawWindow( );
lb.DrawWindow( );
b.DrawWindow( );
Window[] winArray = new Window[];
winArray[] = new Window( , );
winArray[] = new ListBox( , , "List box in array" );
winArray[] = new Button( , );
for ( int i = ; i < ; i++ )
112
-
{
winArray[i].DrawWindow( );
} // end for
} // end Main
} // end Tester
:
Window:
Window:
Writing
Drawing
Window:
Window:
Writing
Drawing
drawing Window at ,
drawing Window at ,
string to the listbox: Stand alone list box
a button at ,
drawing Window at ,
drawing Window at ,
string to the listbox: List box in array
a button at ,
.)( DrawWindow .
. Window .
. Window ListBox Window ListBox
. Button
Window[] winArray
winArray[] = new
winArray[] = new
winArray[] = new
= new Window[];
Window();
ListBox(,"List box in array");
Button();
.)( DrawWindow . i
.)( DrawWindow Window
113
#C
()DrawWindow virtual Window
. , ()DrawWindow
override ()DrawWindow
.
.
, , override override .
( )public override void DrawWindow
override .
1 . ListBox
()ListBox.DrawWindow .
, A Window , . A
()Sort Window .
public class Window
{
// ...
}public virtual void Sort( ) {...
}
114
Late binding
Versioning
Dispatch
-
...\class.cs(): warning CS: 'ListBox.Sort( )' hides
inherited member 'Window.Sort( )'.
To make the current member override that implementation,
add the override keyword. Otherwise add the new keyword.
: , .
, . Sort ListBox new
override .
public class ListBox : Window
{
}public new virtual void Sort( ) {...
. override
override .
public class ListBox : Window
{
}public override void Sort( ) {...
: new .
. new , .
ListBox , ()Sort ( )ListBox Window
.
-4-6
,Window . .
Window ()DrawWindow . window .
, .
, . 2
. , , .
, . .
, . ( )DrawWindow
Window Window . Window
.
()Window.DrawWindow Window ()DrawWindow
. , ,
.
abstract .
;) (abstract public void DrawWindow
Abstract
Signature
1
2
115
#C
.( ; )
. abstract ,
abstract public class Window
116
-
} // end for loop
} // end main
} // end class Tester
:
Writing string to the listbox: First List Box
Writing string to the listbox: Second List Box
Drawing a button at ,
,3-6 Window ..
1 2 :
:
'Cannot create an instance of the abstract class or interface 'Window
.
1
-5-6
, .
. sealed
.
.
3-6 Window abstract sealed . .
, .
''ListBox' cannot inherit from sealed type 'Window
, sealed .
-6-6 )( Object
,#C Object Object . .
, .
. . C# , object .
Sealed
117
#C
( )Equals
) (GetHashCode
hash
.
( )GetType
( )ToString
( )Finalize
.
.
118
) ( Console . , ()ToString
()ToString
override
Dog
Console.WriteLine . ()Object.ToString :
;) (public virtual string ToString
public . )
(int Object Object .
: Object .
-7-6
is-a . , .
, . .
. .
#C .
public protected
.
.
base .
public, private protected .
virtual
override . override
. override
.
abstract . .
override .
.
sealed .
#C Object .
119
overload
out ref
get set
.
.
. . overload
. .
.
.
. 1 .
overload-1-7
.
. Time .
Time
Time overLoad . .
Information hiding
. .
overload .
. . .
.
.
;)MyMethod(int p
MyMethod(int p, int p); // different number
MyMethod(int p, string s); // different types
SomeMethod(int p); // different name
void
void
void
void
overload ()MyMethod .
. .
overload .
. 1-7 Time .
DateTime 6 .
1-7
;using System
namespace MethodOverloading
{
public class Time
{
// private member variables
;private int Year
;private int Month
;private int Date
;private int Hour
;private int Minute
;private int Second
// public accessor methods
) (public void DisplayCurrentTime
{
System.Console.WriteLine( "{}/{}/{} {}:{}:{}",Month, Date, Year, Hour,
;) Minute, Second
}
// constructors
) public Time( System.DateTime dt
{
;Year = dt.Year
;Month = dt.Month
;Date = dt.Day
;Hour = dt.Hour
;Minute = dt.Minute
;Second = dt.Second
}
) int Hour, int Minute, int Second
{
;this.Year = Year
;this.Month = Month
;this.Date = Date
;this.Hour = Hour
;this.Minute = Minute
;this.Second = Second
121
#C
}
}
class Tester
{
) (public void Run
{
;System.DateTime currentTime = System.DateTime.Now
;) Time time = new Time( currentTime
;) (time.DisplayCurrentTime
;) Time time = new Time( , , , , ,
;) (time.DisplayCurrentTime
}
) (static void Main
{
;) (Tester t = new Tester
;) (t.Run
}
}
}
:
// ::
// ::
Time .
.
;System.DateTime currentTime = System.DateTime.Now
;)Time time = new Time(currentTime
)public Time(System.DateTime dt
2time 6 .
;)Time time = new Time(
)public Time(int Year, int Month, int Date, int Hour, int Minute, int Second
overload .
overload .
.
-2-7
private .
.
.
private .
. #C .
. . .
.
. Time Hour .
122
. Hour
Hour
.
2-7 .
. Hour
using System;
namespace Properties
{
public class Time
{
// private member variables
private int year;
private int month;
private int date;
private int hour;
private int minute;
private int second;
// create a property
public int Hour
{
get
{
return hour;
}
set
{
hour = value;
}
}
// public accessor methods
public void DisplayCurrentTime( )
{
System.Console.WriteLine("Time: {}/{}/{} {}:{}:{}",month, date, year, hour,
minute, second );
}
// constructors
public Time( System.DateTime dt )
{
year = dt.Year;
month = dt.Month;
date = dt.Day;
hour = dt.Hour;
minute = dt.Minute;
second = dt.Second;
}
}
class Tester
{
public void Run( )
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time( currentTime );
t.DisplayCurrentTime( );
// access the hour to a local variable
int theHour = t.Hour;
// display it
System.Console.WriteLine( "Retrieved the hour: {}",theHour );
// increment it
theHour++;
// reassign the incremented value back through
123
#C
// the property
;t.Hour = theHour
// display the property
;)System.Console.WriteLine( "Updated the hour: {}", t.Hour
}
][STAThread
) (static void Main
{
;) (Tester t = new Tester
;) (t.Run
}
}
}
:
Time : // ::
Retrieved the hour:
Updated the hour:
}{ . set
get . .
.
set value
.
.
2-7 Hour get set .
{
get
{
;return hour
}
set
{
;hour = value
}
}
.
.
;private int hour
-1-2-7 get
get . 2-7 Hour
int . hour .
get
{
;return hour
}
Accessor
124
-
get . Hour
Time . theHour Hour
t .
;)Time t = new Time(currentTime
;int theHour = t.Hour
-2-2-7 set
set . set value
. .
set
{
;hour = value
}
. set
.
set .
;theHour++
;t.Hour = theHour
theHour . Hour t .
theHour value set hour
set .
get .
-3-7
. Time .
()GetTime .
. ()GetTime
. 3-7 .
3-7
;using System
namespace PassByRef
{
public class Time
{
// private member variables
;private int Year
;private int Month
;private int Date
;private int Hour
;private int Minute
;private int Second
// public accessor methods
)(public void DisplayCurrentTime
125
#C
{
System.Console.WriteLine( "{}/{}/{} {}:{}:{}",Month, Date, Year, Hour,
Minute, Second );
}
public void GetTime(int theHour,int theMinute,int theSecond )
{
theHour = Hour;
theMinute = Minute;
theSecond = Second;
}
// constructor
public Time( System.DateTime dt )
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}
class Tester
{
public void Run()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time( currentTime );
t.DisplayCurrentTime();
int theHour = ;
int theMinute = ;
int theSecond = ;
t.GetTime( theHour, theMinute, theSecond );
System.Console.WriteLine( "Current time: {}:{}:{}",theHour, theMinute,
theSecond);
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
}
:
// ::
Current time: ::
. . . 0:0:0
)( GetTime )( GetTime
.
-1-3-7
.
)( GetTime )( Run .
.
126
.
. .
.)( Run )( GetTime
)( GetTime . 3-7
. ref
public void GetTime(ref int theHour,ref int theMinute,ref int theSecond )
{
theHour = Hour;
theMinute = Minute;
theSecond = Second;
}
.)( GetTime
t.GetTime(ref theHour, ref theMinute, ref theSecond);
127
#C
{
;System.DateTime currentTime = System.DateTime.Now
;) Time t = new Time( currentTime
;)(t.DisplayCurrentTime
;int theHour =
;int theMinute =
;int theSecond =
// pass the ints by reference
;) t.GetTime( ref theHour, ref theMinute, ref theSecond
System.Console.WriteLine( "Current time: {}:{}:{}",theHour, theMinute,
;) theSecond
}
)(static void Main
{
;)(Tester t = new Tester
;)(t.Run
}
}
}
:
// ::
Current time: ::
.
ref .
ref .
-2-3-7 out
#C . 4-7
()GetTime .
;int theHour =
;int theMinute =
;int theSecond =
;)t.GetTime( ref theHour, ref theMinute, ref theSecond
()GetTime
. .
'Use of unassigned local variable 'theHour
'Use of unassigned local variable 'theMinute
'Use of unassigned local variable 'theSecond
#C out . #C
. ()GetMethod .
. out
. out .
()GetTime .
) public void GetTime(out int theHour,out int theMinute,out int theSecond
{
;theHour = Hour
;theMinute = Minute
Definite assignment
128
-
;theSecond = Second
}
()Main .
;int theHour
;int theMinute
;int theSecond
;)t.GetTime( out theHour, out theMinute, out theSecond
-4-7
overload .
. ref out .
out .
129
Array
foreach
. #C
#C .
FCL.
.
-1-8
1 #C . .
) .(1-8
. . .
1-8
.
.
Indexed
-1-1-8
#C .
;type[] array-name
:
;int[] myIntArray
. .
][ .
myIntArray . new .
:
;]myIntArray = new int[
5 .
myIntArray.
5 .
#C Heap . myIntArray
Heap . .
.
.
Heap .
-2-1-8
.
:
;]myIntArray = new int[
5 . .
.
null .
.
Button . Button .
;Button[] myButtonArray
.
;]myButtonArray = new Button[
;]Button[] myButtonArray = new Button[
Button myButtonArray
null . Button .
131
#C
-3-1-8
. .
1Length- 0 . Length
.
Employees Tester . 1-8
.
1-8
using System;
namespace Learning_CSharp
{
// a simple class to store in the array
public class Employee
{
public Employee(int empID)
{
this.empID = empID;
}
public override string ToString( )
{
return empID.ToString( );
}
private int empID;
}
public class Tester
{
static void Main( )
{
int[] intArray;
Employee[] empArray;
intArray = new int[];
empArray = new Employee[];
// populate the arrays
for (int i = ;i<intArray.Length;i++)
{
intArray[i] = i*;
}
for (int i = ;i<empArray.Length;i++)
{
empArray[i] = new Employee(i+);
}
// output array values
Console.WriteLine("intArray values:");
for (int i = ;i<intArray.Length;i++)
{
Console.WriteLine(intArray[i].ToString( ));
}
Console.WriteLine("\nemployee IDs:");
for (int i = ;i<empArray.Length;i++)
{
Console.WriteLine(empArray[i].ToString( ));
}
}
}
}
:
intArray values:
132
employee IDs:
Employee .
Employee ()ToString ID Employee .
()Main . .
for . i .1
intArray .
;intArray[i] = i*
i [ [0intArray 2*0 i
2*1 ... i intArray.Lenght .
i 1intArray.Length-.
Employee
null . Employee
. .
-2-8 foreach
foreach . foreach
.
foreach (type identifier in expression) statement
foreach ( int i in
{
(Console.WriteLine
}
foreach ( Employee
{
(Console.WriteLine
}
Iterate
133
#C
-3-8
} { #C .
.
int[] myIntArray = new int[] { , , , , };//
int[] myIntArray = { , , , , };//
#C } { .
. .
-4-8 params
params .
.
()DisplayVals .
)public void DisplayVals(params int[] intVals
.
)foreach (int i in intVals
{
;)Console.WriteLine("DisplayVals {}",i
}
. DisplayVals
.
;)t.DisplayVals(
.
;}int [] explicitArray = new int[] {
;)t.DisplayVals(explicitArray
params .
3-8 params .
3-8
;using System
namespace UsingParams
{
public class Tester
{
) (static void Main
{
;) (Tester t = new Tester
;)t.DisplayVals(
;}int [] explicitArray = new int[] {
;)t.DisplayVals(explicitArray
}
)public void DisplayVals(params int[] intVals
{
134
-
)foreach (int i in intVals
{
;)Console.WriteLine("DisplayVals {}",i
}
}
}
}
.
displayvals 5
displayvals 6
displayvals 7
displayvals 8
displayvals 1
displayvals 2
displayvals 3
displayvals 4
displayvals 5
-5-8
. 10
. .
. 2-8 .
2-8
. 4 .
-1-5-8
.
. .
type [,] array-name
: myRectangularArray
:
;]int [,] myRectangularArray = new int[
4-8 . .
for .
135
#C
4-8
using System;
namespace RectangularArray
{
public class Tester
{
static void Main( )
{
const int rows = ;
const int columns = ;
// declare a x integer array
int[,] rectangularArray = new int[rows, columns];
// populate the array
for ( int i = ; i < rows; i++ )
{
for ( int j = ; j < columns; j++ )
{
rectangularArray[i, j] = i + j;
}
}
// report the contents of the array
for ( int i = ; i < rows; i++ )
{
for ( int j = ; j < columns; j++ )
{
Console.WriteLine( "rectangularArray[{},{}] = {}",i, j,
rectangularArray[i, j] );
}
}
}
}
}
:
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
rectangularArray[]
=
=
=
=
=
=
=
=
=
=
=
=
[ , ] int
[new int [row,cols rectangularArray .
. .
.( )
.
[rectangularArray[ [rectangularArray[
.[ rectangularArray[ [ rectangularArray[
.
. 5-8 .
5-8
136
-
;using System
namespace InitializingMultiDimensionalArray
{
public class Tester
{
) (static void Main
{
;const int rows =
;const int columns =
// imply a x array
= int[,] rectangularArray
{
}{}, {}, {}, {
;}
) for ( int i = ; i < rows; i++
{
) for ( int j = ; j < columns; j++
{
Console.WriteLine( "rectangularArray[{},{}] = {}", i, j,
;) ]rectangularArray[i, j
}
}
}
}
}
=
=
=
=
=
=
=
=
=
=
=
=
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
]rectangularArray[
4-8 .
= int[,] rectangularArrayrectangularArray
{
}{}, {}, {}, {
;}
4 }{ 4
. #C .
.
#C . 3*4
4*3 .
-2-5-8
. .
.
Jagged Arrays
137
#C
.
. .
.
] .
.[
type [] []...
. myJaggedArray
int [] [] myJaggedArray;
.[ 2][4myJaggedArray[
myJaggedArray 6-8
.
.
6-8
using System;
namespace JaggedArray
{
public class Tester
{
static void Main( )
{
const int rows = ;
// declare the jagged array as rows high
int[][] jaggedArray = new int[rows][];
// the first row has elements
jaggedArray[] = new int[];
// a row with elements
jaggedArray[] = new int[];
// a row with elements
jaggedArray[] = new int[];
// the last row has elements
jaggedArray[] = new int[];
// Fill some (but not all) elements of the rows
jaggedArray[][] = ;
jaggedArray[][] = ;
jaggedArray[][] = ;
jaggedArray[][] = ;
jaggedArray[][] = ;
jaggedArray[][] = ;
jaggedArray[][] = ;
jaggedArray[][] = ;
jaggedArray[][] = ;
for ( int i = ; i < ; i++ )
{
Console.WriteLine( "jaggedArray[][{}] = {}",i, jaggedArray[][i] );
}
for ( int i = ; i < ; i++ )
{
Console.WriteLine( "jaggedArray[][{}] = {}",i, jaggedArray[][i] );
}
for ( int i = ; i < ; i++ )
{
Console.WriteLine( "jaggedArray[][{}] = {}",i, jaggedArray[][i] );
}
138
-
) for ( int i = ; i < ; i++
{
;) ]Console.WriteLine( "jaggedArray[][{}] = {}",i, jaggedArray[][i
}
}
}
}
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
]jaggedArray[][
4 .
;][]int[][] jaggedArray = new int[rows
. .
.
// the first row has elements
;]jaggedArray[] = new int[
// a row with elements
;]jaggedArray[] = new int[
// a row with elements
;]jaggedArray[] = new int[
// the last row has elements
;]jaggedArray[] = new int[
.
. for
Length .
) for (int i = ; i < jaggedArray.Length; i++
{
)for (int j = ; j < jaggedArray[i].Length; j++
{
;)]Console.WriteLine("jaggedArray[{}][{}] = {}",i, j, jaggedArray[i][j
}
}
.
Length . .
[rectangularArray[i,j
[jaggedArray[i][j .
139
#C
-6-8
. System.Array .
#C 1-8 .
1-8
()BinarySearch
overload
.
( )Clean
null
( )Copy
()CreateInstance
( )IndexOf
( )LastIndexOf
( )Reverse
( )Sort
Length
( )GetEnumerator
IEnumerater
-7-8
1-8 ()Reverse : . ()Sort
. ()Reverse ()Sort
. #C string int ... .
()Sort IComparable . 7-8
string .
7-8
;using System
namespace ArraySortAndReverse
{
public class Tester
{
) public static void PrintMyArray( string[] theArray
{
) foreach ( string str in theArray
{
;) Console.WriteLine( "Value: {}", str
}
;) "Console.WriteLine( "\n
}
) (static void Main
140
-
{
= String[] myArray
{
""Proust", "Faulkner", "Mann", "Hugo
;}
;) PrintMyArray( myArray
;) Array.Reverse( myArray
;) PrintMyArray( myArray
= String[] myOtherArray
{
"We", "Hold", "These", "Truths",
"To", "Be", "Self","Evident",
;}
;) PrintMyArray( myOtherArray
;) Array.Sort( myOtherArray
;) PrintMyArray( myOtherArray
}
}
}
:
Faulkner
Hugo
Mann
Proust
Hold
Truths
Be
Evident
Evident
Self
To
We
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Proust
Mann
Hugo
Faulkner
We
These
To
Self
Be
Hold
These
Truths
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
Value:
) . (
.
""Proust", "Faulkner", "Mann", "Hugo
()Array.Reverse . .
myOtherArray .
"We", "Hold", "These", "Truths",
"To", "Be", "Self", "Evident",
()Array.Sort .
-8-8
] [ .
new .
1Length-.
for ) ( .
141
#C
foreach .
} { .
params .
.
.
.
Length .
142
1 . .
.
. .
.
.
#C
.
Struct
09177112161 - - C#
-1-9
.
[attributes] [access-modifiers] struct identifier [:interface-list]
members }
{ struct-
. Loaction . 1-9
struct class Location
Location .
. Location x,y . yVal xVal
1-9
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace CreatingAStruct
{
public struct Location
{
private int xVal;
private int yVal;
public Location( int xCoordinate, int yCoordinate )
{
xVal = xCoordinate;
yVal = yCoordinate;
}
public int x
{
get
{
return xVal;
}
set
{
xVal = value;
}
}
public int y
{
get
{
return yVal;
}
set
{
yVal = value;
}
}
public override string ToString( )
{
return ( String.Format( "{}, {}", xVal, yVal ) );
}
}
public class Tester
144
;) {}", loc
;)
;) {}", loc
;) {}", loc
{
) public void myFunc( Location loc
{
;loc.x =
;loc.y =
Console.WriteLine( "In MyFunc loc:
}
) (static void Main
{
Location loc = new Location( ,
Console.WriteLine( "Loc location:
;) (Tester t = new Tester
;) t.myFunc( loc
Console.WriteLine( "Loc location:
}
}
}
Output:
Loc location: ,
In MyFunc loc: ,
Loc location: ,
. Object
. .
. .
.
. .
CLR .
CLR .
. .
;private int xVal =
;private int yVal =
. private
. .
public .
.
2005VS public public private .
Refactor Encapsulate Field VS . public
private get set .
-2-9
new .
1-9 Tester Location :
;)Location loc = new Location(
145
- C# 09177112161 -
-1-2-9
Tester 1-8 Location . locl 200 300 .
Location .
;)Location loc = new Location(
()WriteLine .
;)Console.WriteLine("Loc location: {}", loc
) ( WritLine . Location ) ( .
( )WriteLine . ()ToString
Object .
override.
Loc location: ,
: ToString override
.
;))(Console.WriteLine("Loc location: {}",loc.ToString
.
locl ()myFunc .
;)t.myFunc(loc
()myFunc y,x :
Loc location: ,
) (Main ) ( WritLine .
Location: 200, 300
Locl
()myFunc . class
:
public class Location
. :
Loc location: ,
In MyFunc loc: ,
Loc location: ,
-2-2-9 new
locl ) ( Stack . 1-9 new
.
146
-
Location loc = new Location();
147
- C# 09177112161 -
.
)(static void Main
{
;Location loc
;loc.xVal =
;// loc.yVal =
;)Console.WriteLine(loc
}
.
'Use of unassigned local variable 'loc
y,x .
)(static void Main
{
;Location loc
loc.xVal = ; // assign member variable
loc.yVal = ; // assign member variable
loc.x = ; // use property
loc.y = ; // use property
;)Console.WriteLine(loc
}
. .
.
-3-9
#C .
.
new .
.
public public .
private) . (Refactor Encapsulate Field
.
.
Object override.
.
.
148
) (..
.
. NET. .
1 System.Collections .
1-10
object .
object . ) int (
) object ( . int
) 1-10(.
Collection
- C# 09177112161 -
object .
) ( .
) ( .
2-10 .
2-10
object .
. 4 .
NET. .
-1-10 ArrayList
ArrayList .
.
. .
. .
ArrayList .
Add ArrayList .
ArrayList .
150
-
ArrayList . ArrayList Insert
.
. ArrayList 1-10
1-10
using System;
using System.Collections;
...
ArrayList numbers = new ArrayList();
...
// fill the ArrayList
foreach (int number in new int[12]{10,9,8,7,7,6,5,10,4,3,2,1})
{
numbers.Add(number);
}
...
// remove first element whose value is 7 (the 4th element, index 3)
numbers.Remove(7);
// remove the element that's now the 7th element, index 6 (10)
numbers.RemoveAt(6);
...
// iterate remaining 10 elements using a for statement
for (int i = 0; i != numbers.Count; i++)
{
int number = (int)numbers[i]; // Notice the cast
Console.WriteLine(number);
}
...
// iterate remaining 10 using a foreach statement
foreach (int number in numbers) // No cast needed
{
Console.WriteLine(number);
}
. Count :
. Length
Queue -2-10
. ( - ) FIFO Queue
. 2-10 .(Dequeue)( Enqueue )
2-10
using System;
using System.Collections;
...
Queue numbers = new Queue();
...
// fill the queue
foreach (int number in new int[4]{9, 3, 7, 2})
{
numbers.Enqueue(number);
Console.WriteLine(number + " has joined the queue");
}
...
151
09177112161 - - C#
// iterate through the queue
foreach (int number in numbers)
{
Console.WriteLine(number);
}
...
// empty the queue
while (numbers.Count != 0)
{
int number = (int)numbers.Dequeue();
Console.WriteLine(number + " has left the queue");
}
Stack -3-10
. ( -) LIFO Stack
.(Pop ( ) Push )
. .
. 3-10 .
3-10
using System;
using System.Collections;
...
Stack numbers = new Stack();
...
// fill the stack
foreach (int number in new int[4]{9, 3, 7, 2})
{
numbers.Push(number);
Console.WriteLine(number + " has been pushed on the stack");
}
...
// iterate through the stack
foreach (int number in numbers)
{
Console.WriteLine(number);
}
...
// empty the stack
while (numbers.Count != 0)
{
int number = (int)numbers.Pop();
Console.WriteLine(number + "has been popped off the stack");
}
HashTable -4-10
. ArrayList
.
152
. 1 . HashTable
object .
. / Hash
.
HashTable :
HashTable . Add
. ][
/ .
ContainKey HashTable .
foreach HashTable
DictionaryEntry . DictionaryEntry
Key Value .
4-10 .
4-10
;using System
;using System.Collections
...
;)(Hashtable ages = new Hashtable
...
// fill the SortedList
;ages["John"] = 41
;ages["Diana"] = 42
;ages["James"] = 13
;ages["Francesca"] = 11
...
// iterate using a foreach statement
// the iterator generates a DictionaryEntry object containing a key/value pair
)foreach (DictionaryEntry element in ages
{
;string name = (string)element.Key
;int age = (int)element.Value
;)Console.WriteLine("Name: {0}, Age: {1}", name, age
}
:
James, Age: 13
John, Age: 41
Francesca, Age: 11
Diana, Age: 42
Name:
Name:
Name:
Name:
-5-10 SortedList
SortedList HashTable . .
. / SortedList
Associative
153
- C# 09177112161 -
. SortedList )
( . / SortedList
.
HashTable SortedList . foreach
SortedList DictionaryEntry .
DictionaryEntry Key .
5-10 .
HashTable SortedList .
5-10
;using System
;using System.Collections
...
;)(SortedList ages = new SortedList
...
// fill the SortedList
;ages["John"] = 3V
;ages["Diana"] = 40
;ages["James"] = 12
;ages["Francesca"] = 10
...
// iterate using a foreach statement
// the iterator generates a DictionaryEntry object containing a key/value pair
)foreach (DictionaryEntry element in ages
{
;string name = (string)element.Key
;int age = (int)element.Value
;)Console.WriteLine("Name: {0}, Age: {1}", name, age
}
.
Diana, Age: 40
Francesca, Age: 10
James, Age: 12
John, Age: 39
Name:
Name:
Name:
Name:
-6-10 BitArray
BitArray . 1 0 1 true 0 false
. . 1-10
BitArray .
1-10 BitArray
overload .
overLoad .
(BitArray(bool[] bits
(BitArray(int[] bits
(BitArray(int count,bool default
154
:And And
BitArray BitArray
.
:Get BitArray .
:IsReadOnly true
}{;get
false .
:Item
.
:Length
.
:Not 1 .
()BitArray Not
BitArray .
:Or or BitArray
. BitArray .
(void Set(int index, bool value
:Set .
:SetAll true false
.
:Xor BitArray xor
.
()GetEnumerator .
IEnumerable
()Clone .
IClonable
ICollection
SyncRoot .
. Employee
.
6-10
;using System
155
09177112161 - - C#
using System.Collections;
namespace
Arshia.CsharpBook{
public
class
Starter{
public static void Main(){
Employee ben=new Employee();
ben.InProfitSharing=false;
ben.InHealthPlan=false;
Employee Valerie=new Employee();
Valerie.InProfitSharing=false;
Participation("Ben",ben);
Participation("Valerie",Valerie);
}
public static void participation(string name, Employee person)
{
Console.WriteLine(name+":");
if (person.InProfitSharing)
{
Console.WriteLine("participating in "+ "Profit Sharing");
}
if (person.InHealthPlan)
{
Console.WriteLine("participating in "+"Health Plan");
If (person.InCreditUnion)
{
Console.WriteLine("participating in " + "Credit Union");
}
}
}
public class Employee
{
public Employee()
{
eFlags.SetAll(true);
}
private BitArray eFlags=new BitArra(3);
public bool InProfitSharing
{
set
{
eFlags.Set(0,value);
}
get
{
return eFlags.Get(0);
}
public bool InHealthPlan
{
set
{
eFlags.Set(1,value);
}
get{
return eFlags.Get(1);
}
public bool InCreditUnion
{
set
{
eFlags.Set(2,value);
}
get
{
156
-
;)return eFlags.Get(2
}
}
}
}
-7-10
.
.
object .
.
.
/ . .
. ReadOnly .
-8-10
.
.
ArrayList . . 52
13 .
.
.
.
-9-10
object .
FCL .
.
.
157
generic
:
generic
generic
generic
generic FCL
-1-11 generic
generic generic .
generic
.
>public class MyGeneric <T
;{ private T member
)Public void Method (T obj
{
}
}
Helper
Template
generic
. Stack generic .
public class Stack<T>
{
T[] m_Items;
public void Push(T item)
{...}
public T Pop( )
{...}
}
Stack<int> stack = new Stack<int>( );
stack.Push();
stack.Push();
int number = stack.Pop( );
. generic T Stack
public class Stack<T>
{...}
#C
;) (>Stack<int> stack = new Stack<int
. ) ( T
T .
-2-11 generic
generic #C ++C .
. generic C++ #C
. ++C
. ) (inline
generic .
++C . .
generic 2,0NET . CLR IL . #C
IL . IL
. generic generic .
.
generic generic
.. generic
generic .
IDE .
NET. IL generic .
.
JIT generic
IL . generic
JIT
.
JIT generic object
IL . .
JIT . Heap
.
Linker
160
1 generic-3-11
2,0CLR
CLR IL generic
:
Point<double> point;
point.X = ;
point.Y = ;
generic -4-11
generic . generic
. 2-11
2-11
class Node<K,T>
{
public K Key;
public T Item;
public Node<K,T> NextNode;
public Node( )
{
Key = default(K);
Item = default(T);
NextNode = null;
}
public Node(K key,T item,Node<K,T> nextNode)
{
Key = key;
Item = item;
NextNode = nextNode;
}
}
public class LinkedList<K,T>
{
Node<K,T> m_Head;
public LinkedList( )
Apply
161
#C
{
;) (>m_Head = new Node<K,T
}
)public void AddHead(K key,T item
{
;)Node<K,T> newNode = new Node<K,T>(key,item,m_Head.NextNode
;m_Head.NextNode = newNode
}
}
.
>class Node<K,T
}{...
) (generic K ) (generic T .
. generic K T .
>public class LinkedList<K,T
}{...
generic ()AddHead .
;)public void AddHead(K key,T item
generic .
generic .
m_Head <Node<K,T m_Head .
generic K T .
;Node<K,T> m_Head
. generic
.
)public void AddHead(K key,T item
{
;)Node<K,T> newNode = new Node<K,T>(key,item,m_Head.NextNode
;m_Head.NextNode = newNode
}
generic
:
>public class LinkedList<U,V
}{...
m_Head :
;Node<KeyType,DataType> m_Head
.
int string .
;) (>LinkedList<int,string> list = new LinkedList<int,string
;)"list.AddHead(,"AAA
:
162
-
;) (>LinkedList<DateTime,string> list = new LinkedList<DateTime,string
;)"list.AddHead(DateTime.Now,"AAA
-5-11 generic
generic #C generic IL
. generic generic
.
. #C
generic . :
generic
.
generic .
generic .
generic IDE
generic ) . (
: generic
.
object generic .
generic .
.
.
.
2-11 .
>public class LinkedList<K,T
{
)T Find(K key
}{...
]public T this[K key
{
get
{
;)return Find(key
}
}
}
:
163
#C
;) (>LinkedList<int,string> list = new LinkedList<int,string
;)"list.AddHead(,"AAA
;)"list.AddHead(,"BBB
;]string item = list[
;)"Debug.Assert(item == "BBB
. ()Find :
)T Find(K key
{
;Node<K,T> current = m_Head
)while(current.NextNode != null
{
if(current.Key == key) //Will not compile
{
;break
}
else
{
;current = current.NextNode
}
}
;return current.Item
}
:
)if(current.Key == key
K == . .
== IComparable .
public interface IComparable
{
;)int CompareTo(object obj
}
. ()Find
.
)if(current.Key.CompareTo(key) ==
K IComparable
.
. .
)if(((IComparable)(current.Key)).CompareTo(key) ==
IComparable .
.
-1-5-11
2,0C# where . where
generic : .
()Find LinkedList .
public class LinkedList<K,T> where K : IComparable
164
-
{
)T Find(K key
{
;Node<K,T> current = m_Head
)while(current.NextNode != null
{
)if(current.Key.CompareTo(key) ==
{
;break
}
else
{
;current = current.NextNode
}
}
;return current.Item
}
//Rest of the implementation
}
IComparable
.
<IComparable<T .
System
generic
<IComparable<T .
.
>public class LinkedList<K,T> where K : IComparable<K
}{...
LinkedList 1 .
<IComparable<T
.
generic .:
public class LinkedList<K,T> where K : IComparable<K>,IConvertible
}{...
Concrete
165
#C
generic .
>public class LinkedList<K,T> where K : IComparable<K
where T : ICloneable
}{...
-2-5-11
generic generic .
.
. #C generic
public . ()new .
<generic Node<K,T 2-11 .
) (class Node<K,T> where K : new
) (where T : new
{
;public K Key
;public T Item
;public Node<K,T> NextNode
) (public Node
{
;) (Key = new K
;) (Item = new T
;NextNode = null
}
//Rest of the implementation
. .
) (public class LinkedList<K,T> where K : IComparable<K>,new( )where T : new
}{...
-3-5-11 /
generic ) bool int
(...
public class MyClass<T> where T : struct
}{...
generic :
public class MyClass<T> where T : class
}{...
struct/class
. struct
. .
struct/class struct/class
.
-1-6-11 generic
generic .NET .
:
<ICollection<T
Add(),
,()Clear
Contains(),
CopyTo(),
)(Remove
Count,IsReadOn
ly
<ICollection<T
.
. <generic ICollection<T
IEnumerable .
IEnumerable <ICollection<T
.
<IList<T
Insert(),Remov
eAt(),
IndexOf() Item
<IEnumerable<T
)GetEnumerator
(
<IEnumerator<T
Current
IDictionary
><TKey, TValue
Add(),Contains
)(Key(),Remove
)(,TryGetValue
, Item,Keys,
Values
<IComparer<T
()Compare
<IComparer<T
<IList<T
.
. <ICollection<T IEnumerable
.
foreach
. ()GetEnumerator
<IEnumerator<T .
foreach
. <Ienumerator<T
. <IEnumerator<T
IEnumerator IDisposable .
generic
IEnumerator
()Compare .
generic .
<List<T
<IList<T> ICollection<T
<IEnumerable<T
ArrayList . <List<T
List<T
<generic
.
.
167
#C
Dictionary<TKey
<, TValue
<IDictionary<TKey,TValue
ICollection<KeyValuePair
><<TKey, TValue
IEnumerable<KeyValuePair
<TKey,TValue>>ISerializable
IDeserializationCallback
SortedList<TKey
<, TValue
<IDictionary<TKey,TValue
<Dictionary <Tkey,Tvalue
ICollection<KeyValuePair
><<TKey, TValue
IEnumerable<KeyValuePair
><<TKey, TValue
<LinkedList<T
<ICollection<T
<LinkedList<T
<IEnumerable<T
ISerializable
IDeserializationCallback
<Queue<T
<ICollection<T
<Queue<T FIFO .
<IEnumerable<T
. ()Enqueue
()Dequeue
. ()Peek
.
<Stack<T
<ICollection<T
<Stack<T LIFO .
<IEnumerable<T
.
. ()Push
()Pop
. ()Peek
.
-2-6-11 IEnumerable
foreach <IEnumerable<T .
<generic IEnumerable<T ()GetEnumerator <IEnumerable<T
#C . yield )
3-11 (.
3-11
// for the generic classes
168
;using System
;using System.Collections.Generic
namespace Enumerable
-
{
public class ListBoxTest : IEnumerable<String>
{
private string[] strings;
private int ctr = ;
// Enumerable classes can return an enumerator
public IEnumerator<string> GetEnumerator( )
{
foreach ( string s in strings )
{
yield return s;
}
}
// required to fulfill IEnumerable
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator( )
{
throw new NotImplementedException( );
}
// initialize the list box with strings
public ListBoxTest( params string[] initialStrings )
{
// allocate space for the strings
strings = new String[];
// copy the strings passed in to the constructor
foreach ( string s in initialStrings )
{
strings[ctr++] = s;
}
}
// add a single string to the end of the list box
public void Add( string theString )
{
strings[ctr] = theString;
ctr++;
}
// allow array-like access
public string this[int index]
{
get
{
if ( index < || index >= strings.Length )
{
// handle bad index
}
return strings[index];
}
set
{
strings[index] = value;
}
}
// publish how many strings you hold
public int GetNumEntries( )
{
return ctr;
}
}
public class Tester
{
static void Main( )
{
// create a new list box and initialize
ListBoxTest lbt =
new ListBoxTest( "Hello", "World" );
// add a few strings
169
#C
;) "lbt.Add( "Proust
;) "lbt.Add( "Faulkner
;) "lbt.Add( "Mann
;) "lbt.Add( "Hugo
// test the access
;"string subst = "Universe
;lbt[] = subst
// access all the strings
) foreach ( string s in lbt
{
) if ( s == null
{
;break
}
;) Console.WriteLine( "Value: {}", s
}
}
}
}
:
Hello
Universe
Proust
Faulkner
Mann
Hugo
Value:
Value:
Value:
Value:
Value:
Value:
()Main . ListBoxTest .
Strings 256 . foreach
<IEnumerable<T ()GetEnumerator .
IEnumerator string ()GetEnumerator .
)
{
yield .
()generic GetEnumerator .
IEnumerable
generic . .
-7-11
generic generic
generic
.
170
generic #C ++C .
.
generic #C generic
IL .
generic .
.
generic .
System.Collections.Generic generic .
#C yield .
171
:
. get . set . . - .
-1-12
.
. .
.
-1-1-12
.
32 . .
.
. .
32 .
: . 32
0 1 . 1 true 0 false
.
>> & 1 0 6 bits .
(bits & ( << )) !=
6 false true .
6 0 .
)bits &= ~( <<
6 1 .
)bits |= ( <<
:
.
.
-2-1-12
32 .
int 32 . bits
6 :
]bits[
true 6
bits[] = true
.
. .
bool . . IntBits
IntBits. IntBits
bool .
IntBit .
struct IntBits
{
)public IntBits(int initialBitValue
{
;bits = initialBitValue
}
// indexer to be written here
;private int bits
}
. IntBits
:
struct IntBits
{
...
] public bool this [ int index
{
get
{
;return (bits & ( << index)) !=
}
set
{
if (value) // Turn the bit on if value is true, otherwise turn it off
173
#C
;)bits |= ( << index
else
;)bits &= ~( << index
}
}
...
}
:
.
] [ .
.
this .
this . overload .
set get . set get
..
. get set
:
.
IntBits ] [
.
;int adapted =
;)IntBits bits = new IntBits(adapted
bool peek = bits[]; // retrieve bool at index
bits[] = true; // set the bit at index to true
bits[] = false; // set the bit at index to false
: get set .
. static static
.
/ 1 . get,set .
;bits[] ^= true
;bits[] = bits[] ^ true
: get set .
-2-12
.
.
Combined
174
.
public int this [ string name ] { ... } // okay
: HashTable ) /(
Add .
;)(Hashtable ages = new Hashtable
;)ages.Add("John",
OverLoad .
} public Name this [ PhoneNumber number ] { ...
} public PhoneNumber this [ Name name ] { ...
ref out .
IntBits bits; // bits contains an indexer
Method(ref bits[]); // compile-time error
-3-12
.
.
Data .
struct Wrapper
{
;int[] data
...
public int[] Data
{
} ;get { return this.data
} ;set { this.data = value
}
}
;)(Wrapper wrap = new Wrapper
...
;int[] myData = wrap.Data
;myData[]++
;myData[]++
:
struct Wrapper
{
;int[] data
...
]public int this [int i
{
get
{
175
#C
;]return this.data[i
}
set
{
;this.data[i] = value
}
}
}
.
;)(Wrapper wrap = new Wrapper
...
;]int[] myData = new int[
;]myData[] = wrap[
;]myData[] = wrap[
;myData[]++
;myData[]++
myData Wrapper .
wrapper :
;wrap[]++
-4-12
. set,get .
set,get ; .
. :
interface IRawInt
{
} ;bool this [ int index ] { get; set
}
struct RawInt : IRawInt
{
...
] public bool this [ int index
{
} get { ...
} set { ...
}
...
}
.
get,set Override . :
class RawInt : IRawInt
{
...
] public virtual bool this [ int index
{
} get { ...
} set { ...
}
...
}
. :
struct RawInt : IRawInt
{
...
] bool IRawInt.this [ int index
176
-
{
} get { ...
} set { ...
}
...
}
-5-12
. .
32 .
. .
.
. .
] [ .
/ .
. set,get .
set,get ; .
Combined
177
Overload
overload
#C
operator
Overload
Overload
#C #C
. .
int ... .
.
;)Fraction theSum = firstFraction.Add(secondFraction
.
.
;Fraction theSum = firstFraction + secondFraction
int .
.
.
overload-
-1-13 operator
#C
.
overload . overload + :
)public static Fraction operator+(Fraction lhs, Fraction rhs
.
#C overload operator .
operator . overload + operator + .
:
;Fraction theSum = firstFraction + secondFraction
.
)Fraction.operator+(firstFraction, secondFraction
: .
-2-13 NET.
#C CLS overload ) NET.
VB.NET ) overload .
. + overload ()Add
.
-3-13
Overload #C .
.
.
++ Employee
. overload
.
179
C#
- 09177112161 -
-4-13
Overload )==( #C .
overload )=!( overload . )<(
)>( )=<( )=>( overload.
-5-13
overload ()Equals object
override . NET.
. FCL overload .
. object ()Equals .
)public virtual bool Equals(object o
override Fraction .
()Equals Fraction .
)public override bool Equals(object o
{
) )if (! (o is Fraction
{
;return false
}
;return this == (Fraction) o
}
is . o is Fraction o
Fraction true false .
()GetHashCode override.
-6-13
#C int long long int .
int long int long .
) long (int .
;int myInt = 5
;myLong
myLong = myInt; // implicit
myInt = (int) myLong; // explicit
.
) .(1/15==15 .
4/9 2 .
implicit explicit .
1-13 Fraction .
()GetHashCode .
180
overload-
1-13
public class Fraction
{
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator)
{
Console.WriteLine("In Fraction Constructor(int, int)");
this.numerator=numerator;
this.denominator=denominator;
}
public Fraction(int wholeNumber)
{
Console.WriteLine("In Fraction Constructor(int)");
numerator = wholeNumber;
denominator = 1;
}
public static implicit operator Fraction(int theInt)
{
Console.WriteLine("In implicit conversion to Fraction");
return new Fraction(theInt);
}
public static explicit operator int(Fraction theFraction)
{
Console.WriteLine("In explicit conversion to int");
return theFraction.numerator /theFraction.denominator;
}
public static bool operator==(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator ==");
if (lhs.denominator == rhs.denominator &&lhs.numerator == rhs.numerator)
{
return true;
}
// code here to handle unlike fractions
return false;
}
public static bool operator !=(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator !=");
return !(lhs==rhs);
}
public override bool Equals(object o)
{
Console.WriteLine("In method Equals");
if (! (o is Fraction) )
{
return false;
}
return this == (Fraction) o;
}
public static Fraction operator+(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator+");
if (lhs.denominator == rhs.denominator)
{
return new Fraction(lhs.numerator+rhs.numerator,lhs.denominator);
}
// simplistic solution for unlike fractions
// 1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8
int firstProduct = lhs.numerator * rhs.denominator;
int secondProduct = rhs.numerator * lhs.denominator;
return new Fraction(
181
C#
Fraction : .
. :
)public static implicit operator Fraction(int theInt
{
;)return new Fraction(theInt
}
implicit Fraction
.
.
Fraction :
)public static explicit operator int(Fraction theFraction
{
;return theFraction.numerator /theFraction.denominator
}
. 16/15 .
.
)==( )=!( .
.
Fraction . 4/3 :
8/6 . .
182
overload-
Fraction ) ( .
. :
)public static Fraction operator+(Fraction lhs, Fraction rhs
{
)if (lhs.denominator == rhs.denominator
{
;)return new Fraction(lhs.numerator+rhs.numerator,lhs.denominator
}
) ( .
;int firstProduct = lhs.numerator * rhs.denominator
;int secondProduct = rhs.numerator * lhs.denominator
* return new Fraction(firstProduct + secondProduct,lhs.denominator
;)rhs.denominator
. 2/1 4/3 ) (1
) .(4 ) (3 ) (2
).(6 ) (10
) .(8 ) (10/8 .
()ToString override / .
)(public override string ToString
{
;) (String s = numerator.ToString() + "/" +denominator.ToString
;return s
}
()WriteLine .
)In Fraction Constructor(int, int
f1: 3/4
)In Fraction Constructor(int, int
f2: 2/4
()Main + .
.
;Fraction f3 = f1 + f2
;))(Console.WriteLine("f1 + f2 = f3: {0}", f3.ToString
+ operator .
In operator+
)In Fraction Constructor(int, int
f1 + f2 = f3: 5/4
+ operator f3 .
()Main int Fraction 3f Fraction
4f .
;Fraction f4 = f3 + 5
183
C#
.
implicit conversion to Fraction
)Fraction Constructor(int
operator+
)Fraction Constructor(int, int
+ 5 = f4: 25/4
In
In
In
In
f3
5 Fraction .
Fraction 5/1 . 3f +
4f .
) (5f . 2f .
.
;)Fraction f5 = new Fraction(24
)if (f5 == f2
{
;)) (Console.WriteLine("F5: {0} == F2: {1}",f5.ToString( ),f2.ToString
}
5f . overload .
)In Fraction Constructor(int, int
== In operator
F5: 2/4 == F2: 2/4
-7-13
overload .
#C overload operator .
) NET. VB.NET ) overload .
+ overload ()Add .
Overload #C
.
overload ()Equals object
override .
implicit explicit .
184
:
.
:Form Control .
.
:Form Form
.
:MDI (1 (MDI .
.
NET. : : 2 3
.
: .
GUI )
( . .NET
.
System.Windows.Forms
MainMenu
Context Menu
C#
09177112161 -System.Web.UIWebControls
System.Web.UIMobileControls
.
.NET . .
GUI ) IDE ( VS .
.
VS.NET
. 1 2
.
GUI . Help Tab
. .
-1-14
. Form
System.Windows.Forms.Form .
()Application.Run .
.
.
Form .
-1-1-14
C # .
1-14 .
.
.
1-14
;using System
;using System.Windows.Forms
;using System.Drawing
class MyWinApp
{
)(static void Main
{
// () Create form and invoke it
;)(Form mainForm = new SimpleForm
;)Application.Run(mainForm
}
}
// User Form derived from base class Form
186
Scrollable
Transparent
class SimpleForm:Form
{
;private Button button
)(public SimpleForm
{
;"this.Text = "Hand Made Form
// () Create a button control and set some attributes
;)(button = new Button
;)button.Location = new Point(
;)button.Size = new Size(
;"button.Text= "Status
;)this.Controls.Add(button
// () Create delegate to call routine when click occurs
;)button.Click += new EventHandler(button_Click
}
)void button_Click(object sender, EventArgs e
{
;)"MessageBox.Show("Up and Running
}
}
winform.cs .
csc /t:winform.exe /r:System.Windows.Forms.dll winform.cs
winform . 1-14 .
.
. ) modal(
. (modeless )
.
1-14
.
-1
SimpleForm Form .
()Applicatian.Run .
-2
.
Controls Control.Collection
. Controls.Add . Remove
187
C#
- 09177112161 -
. IDE Add
. .
. Size Location .
.
button.Size = new Size(); // width, height
button.Location = new Point(); //x,y
-3
. -Click1button .
Click .
;)button.Click += new EventHandler(button_Click
EventHandler)C) # buttonl-Click .
.NET2
) ( . partial
class . .
.
.NET
#C .
-2-14 Windows.Forms
Windows.Forms.Form .
.
2-14
-1-2-14 Control
Form Control .
. .
Control .
188
System.Windows.Forms.DLL 50 .
Control . 1
. .
.
.
control
1-14 Control .
1-14
Size
Size .
Location
Point x y
.
Height,Width,
Right,Left,Top
int
Right=Left+WidthButtom=Top + Height
Bounds
.
=Button.Bounds
(New Rectangle (10105060
ClientRectangle
Anchor
.
.
.
Dock
Backcolor
Forecolor
BackGroundImage
.
.
Color .
.
Text
Font
. 2
.
Core
Bold
189
C#
- 09177112161 -
TabIndex
int Tab .
TabStop
Tab
Focused
Visible
MouseButtons
MousePosition
Point .
ModifierKeys
)(Shift,Alt,Ctrl
Cursor
)
( . Cursors
.
Hand .Cross UpArrow Default.
Beam .Arrow WaitCursor.
Handle
int Handle .
Focused
-2-2-14
VS.Net
.
) ( .
. IDE .
.
Size System.Drawing
.
)button.Size = new Size(); // (width, height
button.Size = button.Size; //Assign size to second button
Size .
Click .
)private void button_Click(object sender, System.EventArgs e
Focus
190
{
;)"MessageBox.Show("Up and Running
Button button = (Button) sender; //Cast object to Button
button.Size = new Size(); //Dynamically resize
System.Drawing.Point Location .
x ) y ( - . x
y .
button.Location = new Point(); // (x,y) coordinates
. GroupBox
GroupBox .Form Point .
Bounds .
;)button.Bounds = new Rectangle(,
Rectangle - - .
Dock .
None . . StatusStrip StatusBar Buttom ToolStrip
ToolBar Up . DockStyle Top
Right Left Buttom Fill . Fill
. TextBox .
;TextBox.Dock = DockStyle.Top
3-14 .
3-14
.
.
Form DockPadding
.
Anchor )
( . 4-14 .
6-14
191
C#
- 09177112161 -
.
PictureBox . Panel
Label
.
Anchor AnchorStyles .
) OR(1 .
;)btnPanel.Anchor = (AnchorStyles.Bottom | AnchorStyles.Left
Tab
Tab Tab .
.
Tab
. 5-14 . Tab
.
5-14
. Tab
. Tab .
Tab TabIndex .
TextBox.TabIndex = ; //First item in tab sequence
192
Controls .
.
1 . 5-14
.
int ctrlCt = this.Controls.Count; //
)foreach (Control ct in this.Controls
{
;)(object ob = ct.GetType
MessageBox.Show(ob.ToString()); //Displays type as string
;)MessageBox.Show(ct.Name
. TextBox
System.Forms.Form.TextBox .
. Controls.Count 10
8 . GroupBox .
HasChildren .
2-14 .
2-14
)void IterateThroughControls(Control parent
{
)foreach (Control c in parent.Controls
{
;))(MessageBox.Show(c.ToString
)if(c.HasChildren
{
;)IterateThroughControls(c
}
}
5-14 .
.
refresh
193
C#
- 09177112161 -
-3-2-14 Control
.
.
.
. 2-14
.
2-14
,Click
Doubleclick
,MouseEnter
,MouseLeave
,MouseOver
MouseWheel
MouseDown
Mouse UP
MouseMove
,Keyup
KeyDoun
(Objectsender ,MouseEventArgs e
Keypress
)KeypressEventHardler
,Object sender
(KeypressEventArgs e
Click DoubleClick MouseHover
MouseEnter MouseLeave .
. Mouseover .
.
OnMouseEnter OnMouseLeave .
;)(TextBox userID = new TextBox
;)userID.MouseEnter += new EventHandler(OnMouseEnter
;)userID.MouseLeave += new EventHandler(OnMouseLeave
EventHandler sender Control
.
)private void OnMouseEnter(object sender, System.EventArgs e
{
194
;Control ctrl = (Control) sender
;ctrl.BackColor= Color.Bisque
}
)private void OnMouseLeave(object sender, System.EventArgs e
{
;Control ctrl = (Control) sender
;ctrl.BackColor= Color.White
}
override ) (Control .
OnEventName . .NET
.
Mouseup MouseDown MouseMove EventArgs
MouseEventArgs .
3-14 .
3-14
Button
.
MouseButtons .
Clicks
Delta
.
.
X,y
- .
MousePosition .
.
.
3-14
.
.
3-14
;using System
;using System.Windows.Forms
;using System.Drawing
class MyWinApp
{
)(static void Main
{
;)(Form mainForm = new DrawingForm
;)Application.Run(mainForm
}
}
// User Form derived from base class Form
class DrawingForm:Form
{
Point lastPoint = Point.Empty; // Save coordinates
public Pen myPen; //Defines color of line
195
C#
. Pen .
myPen )
( .
. MouseEventArgs .
.
. sender
. KeyPress KeyPressEventArgs .
Handled true
. KeyChar .
Keychar .
. Handled true
.
.
)private void OnKeyPress(object sender, KeyPressEventArgs e
{
;if (! char.IsDigit(e.KeyChar)) e.Handled = true
}
KeyPress . Alt Shift
. KeyDown KeyUp
. KeyEventsArgs
. 4-14 KeyErentsArgs
.
196
4-14
Alt-Control-Shift
Handled
KeyCode
. Keys.
KeyData
. Keys
.
Modifiers
.
) shift ctrl (Alt
Keys
. 1D 2D .
KeyPress
. ) (Paste Ctrl+V .
KeyDown
KeyPress .
.
KeyDown Ctrl+V Paste true .
KeyPress .
;private bool paste
//Register event handlers for TextBox t.
//They should be registered in this order,
//because the last registered is the
//first executed
;)t.KeyPress += new KeyPressEventHandler(OnKeyPress
;)t.KeyDown += new KeyEventHandler(OnKeyDown
)private void OnKeyDown(object sender, KeyEventArgs e
{
)if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V
{
paste=true; //Flag indicating paste attempt
string msg = string.Format("Modifier: {} \nKeyCode: {} \nKeyData: {}",
;))(e.Modifiers.ToString(),e.KeyCode.ToString(), e.KeyData.ToString
MessageBox.Show(msg); //Display property values
197
C#
09177112161 -}
)private void OnKeyPress(object sender, KeyPressEventArgs e
{
;if (paste==true) e.Handled = true
}
KeyEventArge Ctrl+V .
Modifier: Control
KeyCode: V
KeyData: Control, V
-3-14 Form
Form Control )ScrollableControl
( .
Modal . 5-14
.
5-14
FormBorderStyle .
FormBorderstyle .
FixedD None
FixedSingle Sizable
FixedDialog
ControlBox
close .
MaximizeBox
MinimizeBox
Opacity
.
. 1 . 95 98 .
TransparencyKey .
.
.
AutoScale
ClientSize
DesktopLocation Point
.
StartPosition
.
198
FormStartPosition.
:CenterParent .
:CenterScreen
:Manual DesktopLocation .
: WindowsDefaltLocaton .
MinimumSize
MaximumSize
ShowInTaskBar
Size .
)0 (0 .
. true.
TopLevel
TopMost
TopLevel
TopMost . TopLevel .
TopMost TopMost
.
WindowState
.
FormWindowStart.
Normal,Minimized,Maximized
Owner
OwnedForms
.
Form 1
.
1-3-14
6-14 .
Icon .ico . ControlBox
close . MaximizeBox
MinimizeBox .
6-14
.
modal .
Owned
199
C#
- 09177112161 -
1
opacity . 0 1 1
. 1
TopMost .
1 .
.
1 0/8 .
DeActivate Activated
. .
;)this.Deactivate += new System.EventHandler(Form_Deactivate
;)this.Activated += new System.EventHandler(Form_Activate
)void Form_Deactivate(object sender, EventArgs e
{
;this.Opacity= .
}
)void Form_Activate(object sender, EventArgs e
{
;this.Opacity=
}
. TransparencyKey
.
. .
.
. FormBorderStyle.None
.
.
7-14
Opacity
200
. TransparencyKey
.
. TransparencyKey
BackColor Panel 7-14
. . Color.Red
CustomForm myForm = new CustomForm();
myForm.TransparencyKey = Color.Red;
myForm.FormBorderStyle= FormBorderStyle.None;
myForm.Show();
.
.
PictureBox
. MouseMoveMousUp MouseDown 4-14 .
4-14
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
public class CustomForm : Form
{
private Point lastPoint = Point.Empty; //Save mousedown
public CustomForm()
{
InitializeComponent(); // set up form
//Associate mouse events with pictureBox
pictureBox.MouseDown += new MouseEventHandler(OnMouseDown);
pictureBox.MouseUp += new MouseEventHandler(OnMouseUp);
pictureBox.MouseMove += new MouseEventHandler(OnMouseMove);
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
lastPoint.X = e.X;
lastPoint.Y = e.Y;
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
lastPoint = Point.Empty;
}
//Move the form in response to the mouse being dragged
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (lastPoint != Point.Empty)
{
//Move form in response to mouse movement
int xInc = e.X - lastPoint.X;
int yInc = e.Y - lastPoint.Y;
this.Location = new Point(this.Left + xInc,
this.Top+yInc);
}
}
// Close Window
private void button_Click(object sender, System.EventArgs e)
{
this.Close();
201
C#
09177112161 -}
}
. PictureBox lastPoint
. Location
. lastPoint .
.
StartPosition .
6-14 FormStartPosition .
. Manual .
6-14
. VS
InitializeComponent
Form.Load
Form.Activated
Form.Activated
Form.DeActivated
Form.DeActivated
Load Activated
.
.
.
Form.Closing
Form.Closed
Form.Close
.
Form.Load . )0 (200 -
.
)private void opaque_Load(object sender, System.EventArgs e
{
;)this.DesktopLocation = new Point(
}
.
;)(opaque opForm = new opaque
;opForm.Opacity =
opForm.TopMost = true; //Always display form on top
;opForm.StartPosition = FormStartPosition.Manual
;)opForm.DesktopLocation = new Point(
;)(opForm.Show
Size ClientSize .
. Size .
202
;)this.ClientSize = new System.Drawing.Size(,
.
Screen.PrimeryScreen.WorkingArea .
. .
;int w = Screen.PrimaryScreen.WorkingArea.Width
;int h = Screen.PrimaryScreen.WorkingArea.Height
;)this.ClientSize = new Size(w/,h/
. MinimumSize
MaximumSize . .
//w and h are the screen's width and height
;)this.MaximumSize = new Size(w/,h/
;)this.MinimumSize = new Size(,
-2-3-14
:
Form.ShowDialog Form.Show Control Form.ShowDialog .
Modal .
. .
Form.Show Modeless .
.
.
modeless
:
.
. 6-14 .
.
.
. VS.Net
InitializeComponent .
Form .
.
Close .
. .
203
09177112161 - -
C#
. ) opform) EventHandler
.
. FormActivate .
//Next statement is at beginning of form's code
public opaque opForm;
bool closed = true; //Flag to indicate if opForm exists
//Create new form or give focus to existing one
private void button_Click(object sender, System.EventArgs e)
{
if (closed)
{
closed = false;
opForm = new opaque();
//Call OnOpClose when new form closes
opForm.Closed += new EventHandler(OnOpClose);
opForm.Show(); //Display new form object
} else {
opForm.Activate(); //Give focus to form
}
}
//Event handler called when child form is closed
private void OnOpClose(object sender, System.EventArgs e)
{
closed = true; //Flag indicating form is closed
}
-3-3-14
Alt+Tab
) . Activated
DeActivate . DeActivate (
Activated resume
.
this.Deactivate += new System.EventHandler(Form_Deactivate);
this.Activated += new System.EventHandler(Form_Activate);
//
void Form_Deactivate(object sender, EventArgs e)
{
button.Enabled = false;
button.Text = "Resume";
}
void Form_Activate(object sender, EventArgs e)
{
button.Enabled = true;
}
Closing
CancelEventHandler .
Cancel CancelEventArgs .
. . true .
this.Closing += new CancelEventHandler(Form_Closing);
void Form_Closing(object sender, CancelEventArgs e)
{
204
)if(MessageBox.Show("Are you sure you want to Exit?", "",MessageBoxButtons.YesNo
)== DialogResult.No
{
//Cancel the closing of the form
;e.Cancel = true
}
}
-4-3-14
. .
modeless ). .(8-14 : TextBox
Search .
TextBox .
. .
8-14
Next .
.
.
.
documentText .
txtSearch
.
DocForm documentText myText
documentText . myText public static
DoForm.myText .
public static TextBox myText; //Declare public variable
)private void docForm_Load(object sender, System.EventArgs e
{
;myText = documentText
}
SearchForm txtSearch .
205
09177112161 - -
C#
. SearchForm DocForm
.
SearchForm . DocForm
.
( 5-14 ). SearchPhrase SearchForm ( SelectedText)
DocForm
.
5-14
private void btnSearch_Click(object sender, System.EventArgs e)
{
//Create instance of search form if it does not exist
if (closed)
{
closed= false;
searchForm = new SearchForm(); //Create instance
searchForm.TopMost = true;
searchForm.Closed += new EventHandler(onSearchClosed);
searchForm.StartPosition = FormStartPosition.Manual;
searchForm.DesktopLocation = new Point(this.Right-,this.Top-);
searchForm.SearchPhrase = documentText.SelectedText;
searchForm.Show();
} else
{
searchForm.SearchPhrase = documentText.SelectedText;
searchForm.Activate();
}
}
private void onSearchClosed(object sender, System.EventArgs e)
{
closed= true;
}
. FindNext 6-14
. IndexOf LastIndexOf
.
6-14
private void btnFind_Click(object sender, System.EventArgs e)
{
int ib; //Index to indicate position of match
string myBuff = DocForm.myText.Text; //Text box contents
string searchText= this.txtSearch.Text; //Search string
int ln = searchText.Length; //Length of search string
if (ln>)
{
//Get current location of selected text
int selStart = DocForm.myText.SelectionStart;
206
)if (selStart >= DocForm.myText.Text.Length
{
;ib =
} else
{
;ib = selStart + ln
}
if (!this.chkCase.Checked) //Case-insensitive search
{
;)(searchText = searchText.ToUpper
;)(myBuff = myBuff.ToUpper
}
;)if (this.radDown.Checked)ib =myBuff.IndexOf(searchText,ib
;)if (this.radUp.Checked && ib>ln-)ib =myBuff.LastIndexOf(searchText,ib-,ib-
if (ib >= ) //Highlight text on main form
{
;DocForm.myText.SelectionStart = ib
;DocForm.myText.SelectionLength = txtSearch.Text.Length
}
}
}
-5-3-14
modeless
. .
.
.
. - 1 . NET.
. Owner
. .
. SearchForm TopMost .
- Owner .
;)(opaque opForm = new opaque
opForm.Owner = this; //Current form now owns new form
;)(opForm.Show
.
.
.
OwnedForms
. opForm 2opForm
.
;)(opaque opForm = new opaque
opForm.Owner = this; //Set current form to owner form
;)(opaque opForm = new opaque
opForm.Owner = this; //Set current form to owner form
)for (int ndx=; ndx<this.OwnedForms.Length; ndx++
{
;)(myForms.Text = "Owner: Form - Form"+ndx.ToString
Owner-owned
207
C#
09177112161 -;)(myForms.Show
}
Modal Owner
.
MDI
MDI .
. MDI
.
MDI IsMdiContainer true
. MdiParent .
MDI 9-14 MDI :
.
9-14
MDI .
;this.IsMdiContainer = true
Text .
MDI
MDI . MDI
File Windows
.
208
MainMenu :
MenuItems 0. MenuItem
.
.
VS.Net . 10-14
VS.Net .
.
10-14
.
private
private
private
private
private
MainMenu
MenuItem
MenuItem
MenuItem
MenuItem
mainMenu;
menuItem;
menuItem;
menuItem;
menuItem;
//File
//Edit
//Window
//File - New
.
this.mainMenu
this.menuItem
this.menuItem
this.menuItem
this.menuItem
=
=
=
=
=
new
new
new
new
new
System.Windows.Forms.MainMenu();
System.Windows.Forms.MenuItem("File");
System.Windows.Forms.MenuItem("Edit");
System.Windows.Forms.MenuItem("Window");
System.Windows.Forms.MenuItem("New");
.
. 1 MenuItems
//Add menu items to main menu object
this.mainMenu.MenuItems.AddRange(new
System.Windows.Forms.MenuItem[] {
this.menuItem,
this.menuItem,
this.menuItem});
//Add menu item below File
this.menuItem.MenuItems.Add(this.menuItem);
//Add menu items to Window menu item
this.menuItem.MdiList = true; //Causes child forms to display
this.menuItem.MenuItems.AddRange(newSystem.Windows.Forms.MenuItem[]
{this.menuItem,this.menuItem, this.menuItem, this.menuItem});
//Set menu on form
this.Menu = this.mainMenu;
:
. MenuItems AddRange Add
popup menu
209
C#
- 09177112161 -
true MdiList
Invoice1). 2Invoice 10-14 (.
Menu MainMenu .
.
File-New .
invForm .
//Following is defined in constructor
;)MenuItem.Click += new System.EventHandler(menuItem_Click
)private void menuItem_Click(object sender, System.EventArgs e
{
;)(invForm myForm = new invForm
;myForm.MdiParent = this
mdiCt += mdiCt; //Count number of forms created
;)(myForm.Text= "Invoice" + mdiCt.ToString
;)(myForm.Show
}
Window MDI .
LayoutMdi .
.
)System.EventArgs e
)System.EventArgs e
)System.EventArgs e
)System.EventArgs e
MdiLayout LayoutMdi .
MDI VS.NET
MainMenu ToolBox . :
. )
.(11-14 .
. Click VS.NET.
.
11-14
210
Properties
.
-4-14
.
ContexMenu .
-1-4-14 MenuItem
NET. . .
.
: Enabled true .
:Checked .
:RadioCheck . Checked true .
BreakBar : Break true .
:Shortcut Shortcut .
. &
Alt .
-2-4-14
MainMenu MenuItem ContextMenu
Menu . ContexMenu
popup .
ContexMenu MainMenu .
.
211
09177112161 - -
C#
.
. TextBox
(12-14 ) . TextBox
12-14
-3-4-14
. ContexMenu
this.txtSearch.ContextMenu = this.contextMenu;
txtSearch
:
private void menuItem_Click(object sender, System.EventArgs e)
{
//Sender identifies specific menu item selected
MenuItem conMi = (MenuItem) sender;
string txt = conMi.Text;
//SourceControl is control associated with this event
if(txt == "Azure Background")
this.contextMenu.SourceControl.BackColor = Color.Azure;
if(txt == "White Background")
this.contextMenu.SourceControl.BackColor = Color.White;
if(txt == "Beige Background")
this.contextMenu.SourceControl.BackColor = Color.Beige;
}
context menu
212
sender
SourceControl .
.
-5-14
. 1
. Help
NET. . .
ToolTip . ToolTip .
HelpProvider . CHM .
- HelpRequested
.Control 1F Help .
ToolTip-1-5-14
VS.NET ToolTip .
( string (ToolTip on toolTipl .
.
ToolTip
.
. 13-14 .
. ToolTip
.
7-14 13-14 .
BackGroundImage . )
( . Tag
ToolTip SetToolTip .
13-14
intuitive
213
09177112161 - -
C#
7-14
public class StarMap:Form
{
public StarMap()
{
this.Text = "Star Search";
this.Width=;
this.Height=;
// Place image of constellation on form
this.BackgroundImage= new Bitmap(@"c:\dracoblack.gif");
// Add name of star on Label
Label star = new Label();
Star.Location = new Point();
Star.Size = new Size();
star.Text = "Thuban";
star.Tag = " Alpha Draconis\n> Magnitude: \n>"+ " Light Years";
star.Font = new Font(star.Font, star.Font.Style |FontStyle.Bold);
this.Controls.Add(star);
ToolTip toolTip = new ToolTip();
toolTip.AutoPopDelay= ; // Tool tip displays
// for secs.
// Tool tip text comes from Tag property of Label
toolTip.SetToolTip(star, star.Tag.ToString());
// Add labels for other stars Etamin and Gianfar here ...
}
}
Help 1F -2-5-14
1F .NET . 1F
. 1F Control.HelpRequested
Help Help
. 14-14 .
. Help
. false MaximizeBox MinimizeBox . true HelpButton 214
14-14
.
ShowHelp HelpRequested
Tag .
.
this.date.HelpRequested += new HelpEventHandler(ShowHelp);
this.ssn.HelpRequested += new HelpEventHandler(ShowHelp);
this.ssn.Tag = "Enter as: nnn-nn-nnnn";
this.date.Tag = "Enter as: mm/dd/yyyy";
private void ShowHelp(object sender, HelpEventArgs e)
{
Control reqControl = (Control)sender;
// Technique : Use tag associated with control
MessageBox.Show(reqControl.Tag.ToString());
// Technique : Link to specific text within a CHM file
string anchor = "#"+reqControl.Name;
// ShowHelp invokes a compiled Help file
Help.ShowHelp(reqControl,@"c:\ctest.chm",HelpNavigator.Topic,"customers.htm"
+anchor);
e.Handled = true; // Always set this
}
sender :
Handled . MousePos Handled HelpEventArgs
Point MousePos .
. Help .
. Help Tag
. HTML Help.ShowHelp
a > . Customers.htm Ctest.chm
215
C#
- 09177112161 -
HelpNavigator CHM .
Index FindTableofContents Topic . Help
HTML .
Microsoft HTML Help Workshop .
-3-5-14 HelpProvider
VS.NET . HelpRequested .
. ShowHelp
. HelpProvider .
HelpNameSpace HTML CHM 4 .
.
:ShowHelp -1 Help true .
:HelpNavigator -2 HelpNavigator .
:HelpKeyWord -3 keyword params ShowHelp .
:HelpString -4 Help .
Help ShowHelp false . true
HelpNameSpace . Help
HelpString Help F1 HTML .
-6-14
GUI
.
.
.
-1-6-14
CS . CS
dll . .
: dll .
csc /t:library product.cs customer.cs /out:ADCFormLib.dll
. Products
.
namespace Products
{
public class ProductForm : System.Windows.Forms.Form
{
216
.
// User Form derived from base class Form
class NewProductForm: Products.ProductForm
{
ADCFormlib . VS.NET
-2-6-14
.
.
. .
private
protected . .
Visible false .
Override-3-6-36
.
.
Click .
Override .
Override . .
)private void btn_Clicked(object sender, System.EventArgs e
{
ButtonClicks(); // Have virtual method do actual work
}
)(protected virtual void ButtonClicks
{
;)(this.Close
}
Override .
)(protected override void ButtonClicks
{
// Code to perform any data validation
;)(this.Close
}
217
C#
- 09177112161 -
-4-6-14 VS.NET
VS.NET .
- Add Inherited Form
Project . .
-7-14
.
.
. NET FCL.
.
Control
.
.
Form Control
.
modal
modeless .
MDI .
.
1F .NET HelpRequested .
Help (HTML (.chm
.
218
:
.
: PictureBox .
TextBox .
Timer :ProgressBar .
ProgressBar .
:
.
:
Net. .
.
:
. .
C#
- 09177112161 -
Control .
.
. GUI
. .
.
GUI .
-1-15 NET.
System.Windows.Forms
. Control .
.
1-15 . *
2,0NET . .x1NET . . DataGrid DataGridView
StatusBar StatusStrip Toolbar ToolStrip . 1-15
.
1-15
1-15
220
Button
. Text
Enter ESC
.
CheckBox
.
.
.
CheckBox1.Appearance = Appearance.Button
CheckedListBox
ListBox
.
ComboBox
TextBox
ListBox . TextBox ListBox
.
DataGridView
GridView
DataGridView
DataGridView .
ImageList
.
.
ListView ToolStrip
TreeView .
Label
ListBox
.
.
.
ListView
.
.
MenuStrip
.
.
Panel
MainMenu.
. .
FlowPanlelayaout
TablePanellayaout .
FlowPanlelayaout
TablePanellayaout
PictureBox
221
C#
- 09177112161 -
.
ProgressBar
RadioButton
StatusStrip
.
.
TextBox
TreeView
.
.
. Text
. Image
.
.
.
.
:Flatstyle Flatstyle.Standard Flatstyle.Popup Flatstyle.Flat :
.Flatstyle.System.Standard Flat Popup .
System . .
:Image . Image.FromFile
.
;)"button1.Image =Image.FromFile ("c:\\book.gif
222
:ImageAlign . ContentAlignment
.
;button1 .ImageAlign =ContentAlignment .MiddleRight
:TextAlign ContentAlignment .
Button
Click : Enter
SpaceBar Alt .
& Text .
C Click .
;)(Button btnClose = new Button
btnClose.Text= "&Close"; // Pushing ALT + C triggers event
;)btnClose.Click += new EventHandler(btnClose_Clicked
// Handle Mouse Click, ENTER key, or Space Bar
)private void btnClose_Clicked(object sender, System.EventArgs e
{
;)(this.Close
}
Click .
AcceptButton CancelButton Click Enter
ESC .
: Cancelbutton Click .
Esc .
-2-2-15 CheckBox
. RadioButton
.
)(CheckBox
Constructor : Public
. Text Image
.
CheckBox
: ) (
) ( .
Appearance Appearance.normal Appearance.Button .
2-15 .
// Create traditional check box
;)(this.checkBox1 = new CheckBox
;)this.checkBox1.Location =new System.Drawing.Point(10120
223
C#
2-15
-3-2-15 RadioButton
RadioButton
. .
)(RadioButton
Constructor : Public
.
.
.
Panel GroupBox
. 3-15 GroupBox
.
3-15
224
GroupBox 1-15
.
1-7
using System.Drawing;
using System.Windows.Forms;
public class OperaForm : Form
{
private RadioButton radioButton1;
private RadioButton radioButton2;
private RadioButton radioButton3;
private GroupBox groupBox1;
public OperaForm()
{
this.groupBox1 = new GroupBox();
this.radioButton3 = new RadioButton();
this.radioButton2 = new RadioButton();
this.radioButton1 = new RadioButton();
// All three radio buttons are created like this
// For brevity only code for one button is included
this.radioButton3.BackColor = Color.Transparent;
this.radioButton3.Font = new Font("Microsoft Sans Serif",8,25F,
FontStyle.Bold);
this.radioButton3.ForeColor =SystemColors.ActiveCaptionText;
this.radioButton3.Location = new Point(16, 80);
this.radioButton3.Name = "radioButton3";
this.radioButton3.Text = "Parsifal";
// Group Box
this.groupBox1 = new GroupBox();
this.groupBox1.BackgroundImage =Image.FromFile("C:\\opera.jpg");
this.groupBox1.Size = new Size(120, 112);
// Add radio buttons to groupbox
groupBox1.Add( new Control[]{radioButton1,radiobutton2,radioButton3});
}
}
225
C#
- 09177112161 -
-4-2-15GroupBox
GroupBox .
.
. Enabled
False .
)(GroupBox
Constructor : public
-5-2-15 Panel
.
GroupBox . ScrollableClass .
)(Panel
Constructor : public
.
Panel .
GroupBox Panel
GroupBox Panel.
Panel .
.
. NET.
Panel :
FlowLayoutPanel . TableLayoutPanel
-6-2-15 FlowLayoutPanel
4-15 FlowLayoutPanel .
4-15
226
FlowDirection .
WrapControls
.
. FlowDirection
FlowLayoutPanel flp = new FlowLayoutPanel();
flp.FlowDirection = FlowDirection.LefttoRight;
// Controls are automatically positioned left to right
flp.Controls.Add(Button1);
flp.Controls.Add(Button2);
flp.Controls.Add(TextBox1);
flp.Controls.Add(Button3);
this.Controls.Add(flp); // Add container to form
TableLayoutPanel -7-2-15
. TableLayoutPanel 5-15
5-15
. TableLayoutPanel
Inset
. .
TableLayoutPanel tlp = new TableLayoutPanel();
// Causes the inset around each cell
tlp.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset;
tlp.ColumnCount = 2; // Grid has two columns
tlp.RowCount = 2; // Grid has two rows
// If grid is full add extra cells by adding column
tlp.GrowStyle = TableLayoutPanelGrowStyle.AddColumns;
// Padding (pixels)within each cell (left, top, right, bottom)
tlp.Padding = new Padding(1145);
tlp.Controls.Add(Button1);
tlp.Controls.Add(Button2);
// Other controls added here
. GrowStyle
. AddColumns .
None . None AddRows
.
227
C#
- 09177112161 -
-8-2-15 Label
.
)(constructor: public Label
. Text
. BorderStyle Image TextAlign .
6-15 .
;)(Label imgLabel = new Label
;imgLabel.BackColor= Color.White
;)"Image img = Image.FromFile("c:\\rembrandt.jpg
;imgLabel.Image= img
;imgLabel.ImageAlign= ContentAlignment.TopCenter
;"imgLabel.Text="Rembrandt
;imgLabel.TextAlign= ContentAlignment.BottomCenter
;imgLabel.BorderStyle= BorderStyle.Fixed3D
;)imgLabel.Size = new Size(img.Width+10, img.Height+25
6-15
228
. : Normal -3
. :StretchImage -4
. PictureBox 7-15
.
.
7-15
229
09177112161 - -
C#
tn1.Image = Image.FromFile("C:\\schiele1.jpg");
tn1.Location = new Point(8, 16);
tn1.Name = "tn1";
tn1.Size = new Size(56, 56);
tn1.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(tn1);
// Code for other thumbnails would go here
// Button to clear picture box
btnClear.Location = new Point(136, 192);
btnClear.Name = "btnClear";
btnClear.Size = new Size(88, 24);
btnClear.Text = "Clear Image";
this.Controls.Add(btnClear);
btnClear.Click += new EventHandler(this.btnClear_Click);
// Set up event handlers for double click events
tn1.DoubleClick += new EventHandler(ShowPic);
tn2.DoubleClick += new EventHandler(ShowPic);
TextBox -2-3-15
TextBox
.
.
constructor: public TextBox()
. TextBox
. 8-15 .
8-15
230
Text AppendText .
= tPoetry.Text
;""In Xanadu did Kubla Khan\r\na stately pleasure dome decree,
;)"txtPoetry.AppendText("\r\nWhere Alph the sacred river ran
Readonly TextBox .
PasswordChar ) ( .
TextBox
) ( . TextBox AcceptsReturn
. False TextBox Enter .
. AcceptsReturn
. AcceptsReturn ) MultiLine True
: :
;"txtPoetry.Text = "Line 1\r\nLine 2
;"txtPoetry.Text = "Line 1"+Environment.NewLine+"Line 2
231
C#
- 09177112161 -
ListBox
ListBox Items . ListBox
) (ADO.NET Add . Sorted False
. Insert
.
;)"lstArtists.Items.Add("Monet
;)"lstArtists.Items.Add("Rembrandt
;)"lstArtists.Items.Add("Manet
lstArtists.Items.Insert(0, "Botticelli"); //Place at top
: ListBox
ListBox.BeginUpdate ListBox.EndUpdate
.
TextBox . ListBox ToString
System.Object override .
ListBox .
// Instances of this class will be placed in a ListBox
public class Artist
{
;public string BDate, DDate, Country
;private string firstname
;private string lastname
public Artist(string birth, string death, string fname,
)string lname, string ctry
{
;BDate = birth
;DDate = death
;Country = ctry
;firstname = fname
;lastname = lname
}
232
9-15
ListBox
. ListBox SelectionMode
.MultiExtended MultiSingle Single None : SelectionMode
MultiExtended . SpaceBar MultiSingle
. Ctrl Shift
. ListBox SelectedIndexChanged
.
ListBox .
. 9-15 .
// Set up event handler in constructor
lstArtists.SelectedIndexChanged += new EventHandler(ShowArtist);
//
private void ShowArtist(object sender, EventArgs e)
{
// Cast to artist object in order to access properties
Artist myArtist = lstArtists.SelectedItem as Artist;
233
C#
SelectedItem ListBox . as
myArtist Artist . SelectedIndex
.
;myArtist = lstArtists.Items[lstArtists.SelectedIndex] as Artist
ListBox .
.
. SelectedItem
.
)foreach (Artist a in lstArtists.SelectedItems
;)MessageBox.Show(a.GetLName
SetSelected .
SelectedIndexChanged . SetSelected
.
)for (int ndx =0; ndx < lstArtists.Items.Count-1; ndx ++
{
;Artist a = lstArtists.Items[ndx] as Artist
;)if (a.country == "Fr") lstArtists.SetSelected(ndx,true
}
ListBox
ListBox MenuItem ComboBox TabControl .
. .
ListBox DrawMode DrawMode
OwnerDrawFixed : .OwnerDrawVariable .
. DrawItem
.
ListBox DrawMode
DrawItem .
;lstArtists.DrawMode = DrawMode.OwnerDrawFixed
lstArtists.ItemHeight = 16; // Height (pixels) of item
;)lstArtists.DrawItem += new DrawItemEventHandler(DrawList
234
BackColor
Bounds
Rectangle
Font
ForeColor
Graphics
Graphics
.
Index
State
.
DrawItemState . ListBox ( (1Selected ) (0 .
)(DrawBackground
)(DrawFocusRectangle
235
C#
09177112161 -;)e.Graphics.DrawRectangle(Pens.Black,rect
{ } else
;ctry = a.Country
Brush b; // Object used to define backcolor
// Each country will have a different backcolor
b = Brushes.LightYellow; // Netherlands
;if (ctry == Fr) b = Brushes.LightGreen
;if (ctry == It) b = Brushes.Yellow
};)e.Graphics.FillRectangle(b,rect
;)e.Graphics.DrawString(artistName,e.Font, Brushes.Black,rect
}
}
ComboBox Text
SelectedItem .
ComboBox .
. ListBox.
;)(ComboBox cbArtists = new ComboBox
;)cbArtists.Size = new System.Drawing.Size(120, 21
cbArtists.MaxDropDownItems= 4; // Max number of items to display
cbArtists.DropDownWidth = 140; // Width of drop-down portion
;)) "cbArtists.Items.Add(new Artist("1832", "1883","Edouard", "Manet","Fr
// Add other items here...
CheckedListBox ListBox
.
.
CheckOnClick True .
CheckedListBox
CheckedItems .
Artist .
// List all items with checked box.
)foreach (Artist a in clBox.CheckedItems
MessageBox.Show(a.ToString()); // > Monet, Claude
.
236
)for (int i=0; I< clBox.Items.Count; i++
{
)if(clBox.GetItemCheckState(i) == CheckState.Checked
{
Do something
} else
{
do something if not checked
}
ListView .
ListView
ListView .
;)(ListView listView1 = new ListView
ListView
// Set the view to show details
;listView1.View = View.Details
View 5 .
237
C#
- 09177112161 -
:Details .
.
:LargeIcon .
:List .
.
:SmallIcon .
:Tile
. WinXP 2003 .
: ListView.View
.
Details
.
// Allow the user to rearrange columns
;listView1.AllowColumnReorder = true
// Select the entire row when selection is made
;listView1.FullRowSelect = true
// Display grid lines
;listView1.GridLines = true
// Sort the items in the list in ascending order
;listView1.Sorting = SortOrder.Ascending
Details .
Columns.Add . :
)ListView.Columns.Add(caption, width, textAlign
Caption Width . . 1-
2-
.
// Create column headers for the items and subitems
;)listView1.Columns.Add("Artist", -2, HorizontalAlignment.Left
;)listView1.Columns.Add("Born", -2, HorizontalAlignment.Left
;)listView1.Columns.Add("Died", -2, HorizontalAlignment.Left
;)listView1.Columns.Add("Country", -2, HorizontalAlignment.Left
238
cHeader.TextAlign = HorizontalAlignment.Left;
ListView.Columns.Add(ColumnHeader cHeader);
ListView
. overload ListView
. .
. 8-15 overload
// Create item and three subitems
ListViewItem item1 = new ListViewItem("Manet",2);
item1.SubItems.Add("1832");
item1.SubItems.Add("1883");
item1.SubItems.Add("France");
// Create item and subitems using a constructor only
ListViewItem item2 = new ListViewItem (new string[]
{"Monet","1840","1926","France"}, 3);
// Create item and subitems with blue background color
ListViewItem item3 = new ListViewItem
(new string[] {"Cezanne","1839","1906","France"}, 1,Color.Empty,
Color.LightBlue, null);
. ListView Items
// Add the items to the ListView
listView1.Items.AddRange(new ListViewItem[]{item1,item2,item3,item4,item5});
LargeImageList : ListView
. SmallImageList LargeIcon
. ListViewItem imageIndex
.
ImageList
. SmallImageList LargeImageList
// Create two ImageList objects
ImageList imageListSmall = new ImageList();
ImageList imageListLarge = new ImageList();
imageListLarge.ImageSize = new Size(5050); // Set image size
// Initialize the ImageList objects
// Can use same images in both collections since they're resized
imageListSmall.Images.Add(Bitmap.FromFile("C:\\botti.gif"));
imageListSmall.Images.Add(Bitmap.FromFile("C:\\cezanne.gif"));
imageListLarge.Images.Add(Bitmap.FromFile("C:\\botti.gif"));
imageListLarge.Images.Add(Bitmap.FromFile("C:\\cezanne.gif"));
// Add other images here
239
C#
1 cezanne.gif . ImageList
. ImageList .
ListView 12-15 11-15 View.LargeIcon .
;listView1.View = View.LargeIcon
12-15
ListView
ListView
.
.
foreach
.
)foreach (ListViewItem lvi in listView1.Items
{
;"" = string row
)foreach(ListViewItem.ListViewSubItem sub in lvi.SubItems
{
;row += " " + sub.Text
}
MessageBox.Show(row); // List concatenated subitems
}
. ) (
. ListView .
.
.
ListView.SelectedItems .
)foreach (ListViewItem lvisel in listView1.SelectedItems
240
Click DoubleClick ListView
SelectedIndexChanged .
FocusedItem .
// Set this in the constructor
;)listView1.SelectedIndexChanged +=new EventHandler(lv_IndexChanged
// Handle SelectedIndexChanged Event
)private void lv_IndexChanged(object sender, System.EventArgs e
{
;string ItemText = listView1.FocusedItem.Text
}
Click EventHandler .
MouseDown MouseUp .
MouseDown.
)private void listView1_MouseDown(object sender, MouseEventArgs e
{
;)ListViewItem selection = listView1.GetItemAt(e.X, e.Y
)if (selection != null
{
;)MessageBox.Show("Item Selected: "+selection.Text
}
}
ListView.GetItemAt .
null .
ListView
ListView .
ListViewItemSorter
ListView.Sort . .
-1 ColumnClick .
-2 ListViewItemSorter
.
-3 . IComparer
IComparer.Compare .
.
ListViewItemComparer .
ListViewItemSorter .
// Connect the ColumnClick event to its event handler
;)listView1.ColumnClick +=new ColumnClickEventHandler(ColumnClick
// ColumnClick event handler
)private void ColumnClick(object o, ColumnClickEventArgs e
{
// Setting this property immediately sorts the
// ListView using the ListViewItemComparer object
241
C#
- 09177112161 -
-2-5-15 TreeView
TreeView
. .
TreeNode Nodes . 13-15 TreeView
ListView .
13-15
TreeNode
TreeNode . Tag Text
ImageIndex . Text
TreeView Tag . object .
ImageIndex ImageList TreeView .
.
TreeNode
) 3-15 (.
242
3-15
BackColor, .
ForeColor
Expand(),
)(Collapse
FirstNode, .
LastNode,
NextNode,
PrevNode
Index
.
.
Parent .
Nodes.Add(),
Nodes.Remove(),
Nodes.Insert(),
)(Nodes.Clear
Nodes Insert .
Clear .
)( Clone .
TreeView TreeNode TreeView .
Insert Add Clone 14-15 .
1TreeView .
;TreeNode tNode
// Add parent node to treeView1 control
;)"tNode = treeView1.Nodes.Add("A
// Add child node: two overloads available
;))"tNode.Nodes.Add(new TreeNode("C
;))"tNode.Nodes.Add("D
// Insert node after C
;))"tNode.Nodes.Insert(1,new TreeNode("E
// Add parent node to treeView1 control
;)"tNode = treeView1.Nodes.Add("B
14-15
A B .
A B . A [0.Nodes[1treeView
243
C#
- 09177112161 -
. Add .
.
// Clone first parent node and add to node B
;)(TreeNode clNode = (TreeNode) treeView1.Nodes[0].Clone
;)tNode.Nodes.Add(clNode
// Add and remove node for demonstration purposes
;)"tNode.Nodes.Add("G
;)tNode.Nodes.Remove(tNode.LastNode
TreeView
foreach .
.
)foreach (TreeNode tn in treeView1.Nodes
{
;)MessageBox.Show(tn.Text
// If (tn.IsVisible) true if node is visible
// If (tn.IsSelected) true if node is currently selected
}
treeNode.NextNode.
;]tNode = treeView1.Nodes[0
{ )while (tNode != null
;)MessageBox.Show(tNode.Text
;tNode = tNode.NextNode
}
TreeView AfterSelect
TReeViewEventArgs .
. TreeView . MouseDown
GetNodeAt .
)private void treeView1_MouseDown(object sender, MouseEventArgs e
{
;)TreeNode tn = treeView1.GetNodeAt(e.X, e.Y
)(// You might want to remove the node: tn.Remove
}
TreeView
) (13-15 TreeView
.
ListView .
NET. System.Reflection
. 4-15 TreeView
.
TreeView .
.
244
system.Enum enum
.
using System.Reflection;
//
private void GetEnums()
{
TreeNode tNode=null;
Assembly refAssembly ;
Hashtable ht= new Hashtable(); // Keep track of namespaces
string assem = AssemName.Text; // Textbox with assembly name
tvEnum.Nodes.Clear(); // Remove all nodes from tree
// Load assembly to be probed
refAssembly = Assembly.Load(assem);
foreach (Type t in refAssembly.GetTypes())
{
// Get only types that inherit from System.Enum
if(t.BaseType!=null && t.BaseType.FullName=="System.Enum")
{
string myEnum = t.FullName;
string nSpace =
myEnum.Substring(0,myEnum.LastIndexOf("."));
myEnum= myEnum.Substring(myEnum.LastIndexOf(".")+1) ;
// Determine if namespace in hashtable
if( ht.Contains(nSpace))
{
// Find parent node representing this namespace
foreach (TreeNode tp in tvEnum.Nodes)
{
if(tp.Text == myEnum) { tNode=tp; break;}
}
}
else
{
// Add parent node to display namespace
tNode = tvEnum.Nodes.Add(nSpace);
ht.Add(nSpace,nSpace);
}
// Add Child - name of enumeration
TreeNode cNode = new TreeNode();
cNode.Text= myEnum;
cNode.Tag = t; // Contains specific enumeration
tNode.Nodes.Add(cNode);
}
Assembly Assembly.Load .
. Type Assembly.GetTypes .
refAssembly = Assembly.Load(assem);
foreach (Type t in refAssembly.GetTypes())
enum . Type.FullName
enum Tag Type .
.
. TreeView
. AfterSelect
tvEnum.AfterSelect += new
TreeViewEventHandler(tvEnum_AfterSelect);
245
C#
- 09177112161 -
treeViewEventArgs.Node . Tag
Type GetMembers
MemberInfo . MemberInfo.Name ListView
.
;// ListView lView
;// lView.View = View.List
)private void tvEnum_AfterSelect(Object sender,TreeViewEventArgs e
{
TreeNode tn = e.Node; // Node selected
;ListViewItem lvItem
if(tn.Parent !=null) // Exclude parent nodes
{
lView.Items.Clear(); // Clear ListView before adding items
;Type cNode = (Type) tn.Tag
// Use Reflection to iterate members in a Type
))(foreach (MemberInfo mi in cNode.GetMembers
{
) "__if(mi.MemberType==MemberTypes.Field &&mi.Name != "value
// skip this
{
;)lView.Items.Add(mi.Name
}
}
}
}
246
StatusStrip
StatusStrip . 15-15
. ) (ToolStripLabel
. ToolStripProgressBar
. ProgressBar ToolStripItem .
StatusStripPanel .
5 .
15-15
247
C#
;)this.Controls.Add(statusStrip1
}
)private void timer_Tick(object sender, EventArgs e
{
// Get difference between current datetime
// and form startup time
;)TimeSpan ts = DateTime.Now.Subtract(startDate
string elapsed = ts.Hours.ToString("00") + ":" +ts.Minutes.ToString("00") +
;)"":" + ts.Seconds.ToString("00
;((StatusStripPanel)statusStrip1.Items["clock"]).Text= elapsed
// Advance progress bar
;if (pb.Value == pb.Maximum) pb.Value = 0
pb.PerformStep(); // Increment progress bar
}
StatusStripPanel
. Image .
StatusStripPanel ToolStripLabel .
BorderStyle ToolStripLabel .
-7-15
.
TextBox .
. :
-1 .
-2 .
. Control
System.Windows.Forms.UserControl .
-3 Control .
GUI
. .
248
-1-7-15
. TextBox
. NumericTextBox TextBox
. KeyPress
.
class NumericTextBox: TextBox
{
)(public NumericTextBox
{
;)this.KeyPress += new KeyPressEventHandler(TextBoxKeyPress
}
protected void TextBoxKeyPress(object sender,
)KeyPressEventArgs e
{
;if (! char.IsDigit(e.KeyChar)) e.Handled = true
}
}
DLL .
-2-7-15 UserControl
.
. .
.
.
IDE VS.Net .
VS.NET Windows Control Library .
. Windows Application
Add Add
User Control
.
.
: Panel
.
16-15 .
16-15
249
09177112161 - -
C#
. 1UserControl
public class UserControl1 : System.Windows.Forms.UserControl
{
private Panel panel1;
private RadioButton radAgree;
private RadioButton radDisagree;
private RadioButton radUn;
private Label qLabel;
PanelColor . Text SetQ . 6-15
Choices Choice
.
public enum Choices
{
Agree = 1,
DisAgree = 2,
Undecided = 3,
}
public string SetQ
{
set {qLabel.Text = value;}
get {return(qLabel.Text);}
}
public Color PanelColor
{
set {panel1.BackColor= value;}
get {return(panel1.BackColor);}
}
public Choices Choice
{
get
{
Choices usel;
usel = Choices.Undecided;
if (radDisagree.Checked) usel= Choices.DisAgree;
if (radAgree.Checked) usel = Choices.Agree;
return(usel);}
}
}
UserControl
VS.NET
. . Windows Forms
250
Customize ToolBox
.
17-15 . 1Q 2Q
.
;private usercontrol.UserControl1 Q1
;private usercontrol.UserControl1 Q2
17-15
Form.Load . VS.NET
Property Browser .
;"Q1.SetQ = "The economy is performing well
;"Q2.SetQ = "I'm not worried about the budget deficit.
;Q1.PanelColor = Color.Beige
.
. UserControl Choice
.
)private void button1_Click(object sender, System.EventArgs e
{
)foreach (Control ct in this.Controls
{
)if (ct is usercontrol.UserControl1
{
;UserControl1 uc = (UserControl1)ct
// Display control name and user's answer
;))(MessageBox.Show(ct.Name+" "+uc.Choice.ToString
}
}
}
UserControl
VS.NET Property
Browser / . Misc
251
C#
- 09177112161 -
. 1
.
Property Browser
. PanelColor.
[Browsable(true),Category("QControl"),Description("Color of panel behind
])"question block
public Color PanelColor
{
};set {panel1.BackColor = value
};)get {return (panel1.BackColor
}
Browsable . true .
Property
Browser .
.
.
-8-15
GUI NET. .
. ) (MouseDown .
DoDragDrop . :
DragDropEffects
) . 4-15 (.
4-15
All
.
Copy .
Link .
Move .
Category
252
None Graphics
. .
Scroll .
DoDragDrop .
AllowDrop true DragEnter
. DragEnter :
.
DragDrop . ) 18-15 (.
18-15
DragDrop .
.
) -15
19 ( TeamA . Available TeamA .
Available .
19-15
.
Ctrl .
) (lstPlayers MouseDown ) (lstTeamA
DragEnter DragDrop:
=lstPlayers.MouseDown +
;)new MouseEventHandler(Players_MouseDown
253
C#
MouseDown ListBox .
DoDragDrop ) Move (Copy
. DragDropEffects FlagsAttribute
. .
.
.
)private void Players_MouseDown(object sender, MouseEventArgs e
{
)if ( lstPlayers.SelectedIndex >=0
{
;string players
;int ndx = lstPlayers.SelectedIndex
;DragDropEffects effect
;)(players = lstPlayers.Items[ndx].ToString
)"" =! if(players
{
// Permit target to move or copy data
effect = lstPlayers.DoDragDrop(players,
;)DragDropEffects.Move | DragDropEffects.Copy
// Remove item from ListBox since move occurred
)if (effect == DragDropEffects.Move
;)lstPlayers.Items.RemoveAt(ndx
}
}
}
DragEnter DragDrop .
DragEventArgs ) . -15
5 (
5-15
. Move .
AllowedEffect
Data
IdataObject .
.
GetData GeTDataPresent .
254
.
Effect
KeyState
-1
8Shift Ctrl
-4
32 Alt
-16
X,Y
x y .
Data.GetDataPresent DragEnter
.
DragDrop Data.GetData
. DataFormats
.
Efffect DragEnter
. DragDropEffects.None DragDrop .
8-15 .
8-15
enum KeyPushed
{
// Corresponds to DragEventArgs.KeyState values
LeftMouse = 1,
RightMouse = 2,
ShiftKey = 4,
CtrlKey = 8,
MiddleMouse = 16,
AltKey = 32,
}
)private void TeamA_DragEnter(object sender, DragEventArgs e
{
;KeyPushed kp = (KeyPushed) e.KeyState
// Make sure data type is string
)))if (e.Data.GetDataPresent(typeof(string
{
// Only accept drag with left mouse key
)if ((kp & KeyPushed.LeftMouse) == KeyPushed.LeftMouse
{
)if ((kp & KeyPushed.CtrlKey) == KeyPushed.CtrlKey
{
e.Effect = DragDropEffects.Copy; // Copy
}
255
C#
09177112161 -else
{
e.Effect = DragDropEffects.Move; // Move
}
}
else // Is not left mouse key
{
;e.Effect = DragDropEffects.None
}
}
else // Is not a string
{
;e.Effect = DragDropEffects.None
}
}
// Handle DragDrop event
)private void TeamA_Drop(object sender, DragEventArgs e
{
// Add dropped data to TextBox
(lstTeamA.Items.Add
;))(string) e.Data.GetData(DataFormats.Text
}
-9-15
7-15 PictureBox
. .
;)(tn1 = new PictureBox
;)"tn1.Image = Image.FromFile("c:\\schiele1.jpg
.jpg1schiele .
:
.
.
GUI .
.
.
.
NET. .
.
256
1
.
.
-1-9-15
: * txt. / * resx. XML
* resources. . .
XML XML .
.
resources . 20-15 resources .
System.Resources .
.
20-15
. .
. English English .
German German .
.
-1 / .
.
);German version (this is a comment
Sattelite
257
C#
09177112161 -Language=German
Select=Whlen Sie aus
Page=Seite
Previous=Vorherig
Next=Nchst
8UTF- resgen .
-3 System.Resources.ResourceManager .
ResourceManager : .
Assembly System.Reflection
. GetString
.
)// new ResourceManager(resource file, assembly
ResourceManager rm = new
;))(ResourceManager("german",Assembly.GetExecutingAssembly
;)"nxtButton.Text= rm.GetString("Next
-4 .
.
csc /t:exe /resource:german.resources myApp.cs
ResourceWriter Resources.
.
.
Resources System.Resources.ResourceWriter .
. ResourceWriter
AddResource .
;)"IResourceWriter writer = new ResourceWriter("myResources.resources
// .Resources output file
;)"Image img = Image.FromFile(@"c:\schiele1.jpg
rw.AddResource("Page","Seite"); // Add string
rw.AddResource("artistwife",img); // Add image
rw.Close(); // Flush resources to the file
ResourceManager
ResourceManager
. .
;)"tn1.Image = Image.FromFile("C:\\schiele1.jpg
ResourceManager .
. GetString GetObject .
ResourceManager rm = new ResourceManager("myresources",
;))(Assembly.GetExecutingAssembly
// Extract image from resources in assembly
;)"tn1.Image = (Bitmap) rm.GetObject("artistwife
258
ResXResourceWriter resx.
ResXResourceWriter ResourceWriter resx.
XML .
. Resource .
;)"ResXResourceWriter rwx = new ResXResourceWriter(@"c:\myresources.resx
;)"Image img = Image.FromFile(@"c:\schiele1.jpg
rwx.AddResource("artistwife",img); // Add image
rwx.Generate(); // Flush all added resources to the file
XML / .
)( . myresources.resx
.
<data name="face" type="System.Drawing.Bitmap, System.Drawing,
Version=1,0,3300,0,Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" mimetype="application/xmicrosoft.
>"net.object.bytearray.base64
<value> ---- Actual Image bytes go here ---></value
: resx.
.
ResXResourceReader resx.
ResXResourceReader ) IdictionaryEnumerator(
resx. . .
;)"ResXResourceReader rrx = new ResXResourceReader("c:\\myresources.resx
// Enumerate the collection of tags
)foreach (DictionaryEntry de in rrx
{
MessageBox.Show("Name: "+de.Key.ToString()+"\nValue: " +
;))(de.Value.ToString
// Output --> Name: artistwife
// --> Value: System.Drawing.Bitmap
}
;)(rrx.Close
resx. resources.
resgen.exe resx. resources. .
resgen myresources.resx myresources.resources
. resources.
resx. . .
VS.NET-2-9-15
VS.NET resx. .
Show All File Solution Explorer .
259
C#
- 09177112161 -
resources. resx. .
ResourceManager .
;))ResourceManager resources = new ResourceManager(typeof(Form1
NET. .
. NET. .
.
German French .
.
CultureInfo .
DLL .
VS.NET
Localizable true .
resx. .
resx. .
) .(en-us
. .
. MSDN CultureInfo
.
.
21-15
properties Language
. resx.
.
. 21-15
) 22-15( . DLL
22-15
260
CurrentThread.CurrentUICulture
. ResourceManager
. )
( . .
: CurrentUICulture
. ()InitializeComponent German
.
= System.Threading.Thread.CurrentThread.CurrentUICulture
;)"new System.Globalization.CultureInfo("de-DE
VS.NET
.
.
resx. French Canadian .
:
-1 resx. resources. .
filmography.Form1.fr-CA.resources
fr-CA Release .
.
-10-15
261
C#
- 09177112161 -
.
System.Windows.Forms.Control Control
.
. Panel GroupBox .
TextBox .
.
PictureBox SizeMode
.
ListBox . ComboBox
. .
TreeView ListView .
ListView .
TreeView .
. DoDragDrop
.
NET. .
.
262
Open .
Save .
Font .
Color .
Print .
VC 2005 .
.
.
.
-1-16 MessageBox
MessageBox
. " .
.
OK .
1-16 .
.
C#
- 09177112161 -
1-16
.
. ) (
) (
. OK Cancel
.
.
.
.
MessageBox .
Show .
. .
1-16 . 1-16
. "
:
1-16
Asterisk Information
Exclamation Warning
Question
None
:
. 2-16
:
2-16
Ok
264
OkCancel
RetryCancel
YesNo
Ok Cancel.
Retry Cancel.
Yes No.
YesNoCancel
Yes No Cancel.
:
.
.
Enter .
MessageBoxDefaultButton 3-16 :
3-16
Button1
Button2
Button3
. Yes No Cancel
Cancel .
Yes No Yes .
MessageBoxOptions
4-16 :
RightAlign
RTLReading
.
)
(. .
Show
Show MessageBox .
Show 2-16 .
265
C#
- 09177112161 -
. .
.
MessageBox.Show("My Text", "My Caption", MessageBoxButtons.OKCancel,
;)MessageBoxIcon.Information,MessageBoxDefaultButton.Button1
2-16
Show
MessageBox .
.
.
:
)MessageBox.Show(Text
)MessageBox.Show(Text,Caption
)MessageBox.Show(Text,Caption,Button
)MessageBox.Show(Text,Caption,Button,Icon
)MessageBox.Show(Text,Caption,Button,Icon,DefaultButton
Text
. :
:Caption .
.
:Button MessageBoxButtons . .
Ok .
:Icon MessageBoxIcon .
.
:DefaultButton MessageBoxDefaultButton
.
.
Show DialogResult .
. 5-16
DialogResult .
5-16
266
Abort
Abort Abort
.
Cancel
Cancel
Cancel .
Ignore
Ignore Ignore
.
No
No
No
.
None
None .
.
OK
Ok
Ok .
Retry
Retry Retry
.
Yes
Yes Yes .
.
.
.
-1-16
2005VS (1 Windows Application SimpleMessageBox
.
(2 Text SimpleMessageBox .
(3 Button Name btnShow
Text Show .
(4 Label .
. Name lblResult Text NothingClicked .
3-16.
3-16
267
C#
- 09177112161 -
(5 Show Click .
.
)private void btnShow_Click(object sender, EventArgs e
{
if ( MessageBox.Show("Your Internet Connection will be closed now!","Dial-Up
Networking Notification",MessageBoxButtons.OKCancel, MessageBoxIcon.None,
)MessageBoxDefaultButton.Button1) == DialogResult.OK
{
;"!lblResult.Text = "OK Clicked
// Call some method here...
}
else
{
;"!lblResult.Text = "Cancel Clicked
// Call some method here...
}
}
(6 Show . 4-16 .
4-16
(7 Ok Cancel .
.
\ .
n .
:
.
.
.
-2-16 OpenFileDialog
"
.
268
6-16
OpenFileDialog
6-16 Open ."
)
NotePad (
269
C#
- 09177112161 -
.
.
.
. 6-16
:
6-16
AddExtension
SaveFileDialog
.
CheckFileExist
CheckPathExist
DefaultExt
DereferenceLinks
) ( true ).(false
FileName
FileNames
.
- .
Filter
Open
.
.
InitialDirectory Open .
MultiSelect
ReadOnlyChecked
Readonly Open
RestoreDirectory Open
ShowHelp
Help Open
ShowReadOnly
-
270
Title
Open
.
ValidateNames
OpenFileDialog
OpenFileDialog
ShowDialog . :
:Dispose .
:OpenFile Open - .
FileName .
: Reset OpenFileDialog .
:ShowDialog Open .
ShowDialog .
.
Open
. :
;)(openFileDialog1.ShowDialog
DialogResult OK Cancel . OK
Open Cancel Cancel .
.
.
OpenFileDialog .
OpenFileDialog
OpenFileDialog
.
OpenFileDialog
TextBox .
-2-16 OpenFileDialog
(1 2005VS Dialog .
(2 Dialogs.cs .
(3 Properties :
271
C#
- 09177112161 -
Size 304-456 .
StartPositio CenterScreen .
Text Dialogs .
(4 TextBox .
Button Open .
TextBox Button :
(5
7-16 .
7-16
: Anchor
.
(6 Dialogs FileOpenDialog .
VS .
Properties . "
.
.
(7
. Open :
public partial class Dialogs : Form
{
// Declare variables
;private string strFileName
272
(8 Open btnOpen .
.
.
)private void btnOpen_Click(object sender, EventArgs e
{
// Set the OpenFileDialog properties
;"*openFileDialog1.Filter = "Text files (*.txt) |*.txt|" + " All files (*.*) |*.
;openFileDialog1.FilterIndex = 1
;"openFileDialog1.Title = "Demo Open File Dialog
// Show the OpenFileDialog and if the user clicks the
// Open button, load the file
)if (openFileDialog1.ShowDialog() == DialogResult.OK
{
// Save the file name
;strFileName = openFileDialog1.FileName
// Read the contents of the file
;)txtFile.Text =System.IO.File.ReadAllText(strFileName
}
}
(9 Open
Open . .
Files Of Type .
.
(10 .
Open 8-16 .
(11 " . Open .
Open .
Filter .
:Files Of Type .
)|(
.
.
273
C#
- 09177112161 -
8-16
// Set the OpenFileDialog properties
;"*openFileDialog1.Filter ="Text files (*.txt) |*.txt| All files (*.*) |*.
FilterIndex
. 1
.
;openFileDialog1.FilterIndex = 1
Title Open :
;"openFileDialog1.Title = "Demo Open File Dialog
-3-16 SaveFileDialog
OpenFileDialog
SaveFileDialog
. OpenFileDialog
. SaveFileDialog
.
.
SaveFileDialog . SaveFileDialog OpenFileDialog
.
." OpenFileDialog
.
SavefileDialog
7-16 SaveFileDialog .
) (
.
7-16
274
Createprompt
OverWritePrompt
ResotreDirectory
Save
OpenFileDialog.
SaveFileDialog
SaveFileDialog OpenFileDialog .
OpenFileDialog . OpenFileDialog
ShowDialog Save .
SaveFileDialog
SaveFileDialog .
TextBox .
SaveFileDialog SaveFile
TextBox . .
-3-16 SaveFileDialog
(1 " .
(2 Button .
Name btnSave .
Text Save .
Anchor Top-Right .
Location 38-367 .
(3 Dialogs SaveFileDialog .
(4 btnSave .
:
)private void btnSave_Click(object sender, EventArgs e
{
// Set the save dialog properties
;"saveFileDialog1.DefaultExt = "txt
;saveFileDialog1.FileName = strFileName
;"*saveFileDialog1.Filter ="Text files (*.txt)|*.txt|All files (*.*)|*.
;saveFileDialog1.FilterIndex = 1
;saveFileDialog1.OverwritePrompt = true
275
C#
- 09177112161 -
Save . Save .
(6 ok . TextBox
. Open
" .
(7 OverwritePrompt SaveFileDialog TextBox
Save ." .
9-16 .
Yes
. NO Save .
9-16
: Save Open
.
.
WinZip WinRar .
DefaultExt .
" saveFileDialogl.DefaultExt= " txt
OverwritePrompt Boolean . true
.
false
.
;saveFileDialog1.OverwritePrompt = true
276
-4-16 FontDialog
.
FontDialog .
.
OpenFileDialog SaveFileDialog FontDialog
.
.
FontDialog
8-16 FontDialog .
8-16
AllowScriptChange
Script
Script
true
Script .
Color
Font
FontMustExist
MaxSize
MinSize
ShowApply
Apply
ShowColor
ShowEffects
ShowHelp
Help
277
C#
- 09177112161 -
FontDialog
FontDialog ShowDialog
Reset
.
FontDialog
FontDialog ShowDialog
.
;)(fontDialog1.ShowDialog
10-16 .
10-16
Effects
. ShowEffects true
. Color . ShowColor
false . ShowDialog true
.
;fontDialog1.ShowColor = true
;)(fontDialog1.ShowDialog
ShowDialog ShowDialog DialogResult
. DialogResult.Ok DialogResult.Cancel.
OK Color
Font FontDialog
.
.
.
278
TextBox .
-4-16 FontDialog
(1" .
(2 Button :
Name btnFont .
Anchor Top-Right .
Anchor 68-367 .
Text Font .
(3 FontDialog .
Dialog FontDialog . FontDialog
.
.
(4 btnFont .
:
)private void btnFont_Click(object sender, EventArgs e
{
// Set the FontDialog control properties
;fontDialog1.ShowColor = true
// Show the Font dialog
)if (fontDialog1.ShowDialog() == DialogResult.OK
{
// If the OK button was clicked set the font
// in the text box on the form
;txtFile.Font = fontDialog1.Font
// Set the color of the font in the text box
// on the form
;txtFile.ForeColor = fontDialog1.Color
}
}
(5 . Font Font
11-16 . TextBox OK .
(6 . .
(7 Open .
Open Open . .
.
11-16
279
C#
- 09177112161 -
-5-16 ColorDialog
.
TextBox 2005VS .
font ColorDialog .
ColorDialog
.
ColorDialog 12-16 48
.
12-16
280
ColorDialog
. . 9-16
:
9-16
AllowFullOpen
Custom Color
. false
Define Custom Colors .
AnyColor
Color
CustomColors
Custom Color
.
FullOpen
ShowHelp
Help Color
13-16
.
.
281
C#
- 09177112161 -
ColorDialog ShowDialog .
. .
ColorDialog
Color ShowDialog :
;)(colorDialog1.ShowDialog
DialogResult OK
.Cancel
Color
. .
TextBox :
;txtFile.ForeColor = colorDialog1.Color
.
-5-16 ColorDialog
(1 Dialogs forml.
(2 Button
:
Name btncolor .
Anchor Top-Right .
Location 98-367 .
Text color .
(3 Dialogs ColorDialog .
.
(4 btnColor click .
.
)private void btnColoe_Click(object sender, EventArgs e
{
// Show the Color dialog
)if (colorDialog1.ShowDialog() == DialogResult.OK
{
// Set the BackColor property of the form
;this.BackColor = colorDialog1.Color
}
}
(5 . .
(6 . Color color .
Define Custom Colors
. OK .
282
(7 Ok Color .
(8 Font Color
. ColorDialog .
"
.
-6-16 PrintDialog
" .
.
NET. .
2005#VC PrintDialog .
. .
14-16
PrintDialog .
Print Ok Cancel .
ShowDialog DialogResult.Ok DialogResult.Cancel
if .
14-16
283
C#
- 09177112161 -
PrintDialog
10-16 PrintDialog :
10-16
AllowPrintTofile
Print To File
AllowSelection
Selectin
AllowSomePages
Pages
Document
PrinterSettings
.
.
PrintToFile
Print To File
ShowHelp
Help
ShowNetwork
Network print
PrintDialog
Print ShowDialog . print
14-16 . PrintDialog
. print :
;()PrintDialog.ShowDialog
-1-6-16 PrintDocument
ShowDialog PrintDialog Document
PrintDialog PrintDocument .
PrintDocument )
( . System.Drawing.Printing
.
using .
PrintDocument
PrintDocument 11-16
.
11-16
DefaultPageSettings ) (
284
.
DocumentName
.
Print Status
.
PrintController
PrintController
.
PrinterSettings
Print PrintDocument PrinterSettings
.
PrintPage PrintDocument . Print
.
. StreamReader
.
6-16 PrintDocument
.
-6-16 PrintDialog
(1 VS.NET Dialogs .
(2 Button
:
Name btnPrint .
Anchor Top-Right .
Location 128-367 .
Text Print .
(3 Printing PrintDialog .
.
(4 using :
;using System.IO
;using System.Drawing.Printing
(5 .
// Declare variables
;private string strFileName
;private StreamReader objStreamToPrint
;private Font objPrintFont
285
09177112161 - -
C#
btnPrint ( 6
. .
private void btnPrint_Click(object sender, EventArgs e)
{
// Declare an object for the PrintDocument class
PrintDocument objPrintDocument = new PrintDocument();
// Set the DocumentName property
objPrintDocument.DocumentName = "Text File Print
Demo";
// Set the PrintDialog properties
printDialog1.AllowPrintToFile = false;
printDialog1.AllowSelection = false;
printDialog1.AllowSomePages = false;
// Set the Document property for
// the objPrintDocument object
printDialog1.Document = objPrintDocument;
// Show the Print dialog
if (printDialog1.ShowDialog() == DialogResult.OK)
{
// If the user clicked on the OK button
// If the user clicked on the OK button
// then set the StreamReader object to
// the file name in the strFileName variable
objStreamToPrint = new StreamReader(strFileName);
// Set the printer font
objPrintFont = new Font("Arial", 10);
// Set the PrinterSettings property of the
// objPrintDocument Object to the
// PrinterSettings property returned from the
// PrintDialog control
objPrintDocument.PrinterSettings =
printDialog1.PrinterSettings;
// Add an event handler for the PrintPage event
of
// the objPrintDocument object
objPrintDocument.PrintPage +=
new PrintPageEventHandler(prtPage);
// Print the text file
objPrintDocument.Print();
// Clean up
objStreamToPrint.Close();
objStreamToPrint = null;
}
}
.( 7
private void prtPage(object sender, PrintPageEventArgs e)
{
// Declare variables
float sngLinesPerpage = 0;
float sngVerticalPosition = 0;
int intLineCount = 0;
float sngLeftMargin = e.MarginBounds.Left;
float sngTopMargin = e.MarginBounds.Top;
string strLine;
// Work out the number of lines per page.
// Use the MarginBounds on the event to do this
sngLinesPerpage = e.MarginBounds.Height /
objPrintFont.GetHeight(e.Graphics);
286
// Now iterate through the file printing out each
line.
// This assumes that a single line is not wider than
// the page width. Check intLineCount first so that we
// dont read a line that we wont print
strLine = objStreamToPrint.ReadLine();
while((intLineCount < sngLinesPerpage) &&
(strLine != null))
{
// Calculate the vertical position on the page
sngVerticalPosition = sngTopMargin +
(intLineCount * objPrintFont.GetHeight(e.Graphics));
// Pass a StringFormat to DrawString for the
// Print Preview control
e.Graphics.DrawString(strLine, objPrintFont,
Brushes.Black, sngLeftMargin,
sngVerticalPosition,
new StringFormat());
// Increment the line count
intLineCount = intLineCount + 1;
// If the line count is less than the lines per
// page then read another line of text
if (intLineCount < sngLinesPerpage)
{
strLine = objStreamToPrint.ReadLine();
}
}
// If we have more lines then print another page
if (strLine != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
}
start .( 8
.
. Open ( 9
. 15-16 Print print
. pages selection Print To File
AllowSelection ShowDialog
. false AllowSomePages AllowPrintToFile
. 15-16
. Print ( 10
15-16
287
C#
- 09177112161 -
PrintDocument . :
;()PrintDocument objPrintDocument = new PrintDocument
DocumentName .
.
.
;"objPrintDocument.DocumentName = "Text File Print Demo
PrintDialog .
Print To File Selection Pages
Print . false :
;printDialog.AllowPrintToFile = false
;printDialog.AllowSelection = false
;printDialog.AllowSomePages = false
Print
. Document PrintDialog PrintDocument
.
;printDialog.Document = objPrintDocument
Print . ShowDialog
. DialogResult .
Print DialogResult.Cancel . if
.
Print strFileName
. StreamReader .
288
. strFileName
.
;)objStreamToPrint = new StreamReader(strFileName
. Font Arial
10 .
;)objPrintFont = new Font("Arial",
.
Button
. .
.
Button .
.
PrintDocument
PrintPage .
PrintPage .
PrintPage . prtPage PrintPage
:
;)objPrintDocument.PrintPage += new PrintPageEventHandler(prtPage
PrintDocument .
Print . Print
PrinterSettings
objprintDocument.PrinterSettings .
;objPrintDocument.PrinterSettings =printDialog.PrinterSettings
Print . PrintPage
prtPage .
;)(objPrintDocument.Print
PrintPage . )
void .(. .
. sender Object .
. prtPage PrintPage
)private void prtPage(object sender, PrintPageEventArgs e
.
. sngLeftMargin sngTopMargin
printPageEventArgs .
;float sngLinesPerpage =
;float sngVerticalPosition =
;int intLineCount =
;float sngLeftMargin = e.MarginBounds.Left
289
C#
.
) ( .
MarginBounds.Height e printPageEventArgs )
(.
PrintDialog PrinterSettings .
PrinterSettings
objPrintDocument . objPrintDocumenr PrintPage
PrintPageEventArgs .
sngLinesPerpage = e.MarginBounds.Height /
;)objPrintFont.GetHeight(e.Graphics
sngLinesPerPage .
.
.
. strLine
:
;)(strLine = objStreamToPrint.ReadLine
=! while((intLineCount < sngLinesPerpage) && (strLine
))null
{
.
.
:
sngVerticalPosition = sngTopMargin +
;))(intLineCount * objPrintFont.GetHeight(e.Graphics
:
;intLineCount = intLineCount +
strLine :
)if (intLineCount < sngLinesPerpage
{
;)(strLine = objStreamToPrint.ReadLine
290
" .
. HasMorePages
false Print PrintPage .
HasMorePages true . print
PrintPage prtPage .
)if (strLine != null
{
;e.HasMorePages = true
}
else
{
;e.HasMorePages = false
}
Print
btnPrint-Click .
.
;)(objStreamToPrint.Close
;objStreamToPrint = null
-7-16 FolderBrowserDialog
.
. FolderBrowserDialog
Browse For
Folder .
.
FolderBrowser
. 16-16 FolderBrowser ) (
. Make New Folder
.
16-16
291
C#
- 09177112161 -
FolderBrowser
.
12-16 .
12-16
Description
RootFolder
.
.
SelectedPath
FolderBrowser
Browse For Folder
. " .
Description .
ShowDialog .
RootFolder .
. Environment.SpecialFolder
292
My Documents
. ShowNewFolderButton .
true Make New Folder
.
= folderBrowserDialog.Description
;""Select a folder for your backups:
= folderBrowserDialog.RootFolder
;Environment.SpecialFolder.MyComputer
;folderBrowserDialog.ShowNewFolderButton = false
DialogResult . if
.
SelectedPath .
. temp c c:\temp
.
;strFileName = folderBrowserDialog.SelectedPath
(1 Dialogs.
(2 Button
:
Name btnBrowse .
Text Browse.
Location 158-367.
Anchor Top'Right .
(3 FolderBrowserDialog .
Dialogs FolderBrowserDialog .
.
(4 btnBrowse Click .
:
)private void btnBrowse_Click(object sender, EventArgs e
{
// Set the FolderBrowserDialog control properties
= folderBrowserDialog.Description
;""Select a folder for your backups:
= folderBrowserDialog.RootFolder
;Environment.SpecialFolder.MyComputer
;folderBrowserDialog.ShowNewFolderButton = false
// Show the Browse For Folder dialog
293
C#
(5 . Start .
(6 Browse . Browse For Folder
17-16 .
17-16
(7 Ok .
18-16 .
18-16
-8-16
2005#C .
294
.
.
new .
.
.
295
as is
1 .
.
.
interface
.
. .
.
.
.
.
: #C
.
Interface
is-a .
.
. CanBeBoughtWithABigLoan .
.
.
-1-17
.
[attributes] [access-modifier] interface interface-name[:base}list]{interface-body
. .
internal
.
: Document Document
. IStorable Document .
Document IStorable .
public class Document : IStorable
{
}public void Read() {...
}public void Write(object obj) {...
// ...
}
Document IStorable
297
298
C#
Status
{; int
.
. public
. .
.
Document .
()Write ()Read Status . Document
. IStorable Status .
Document ) ( .
.
-1-1-17
. Document
IStorable ICompressible .
.
.
public class Document : IStorable, ICompressible
Document ICompressible .
)(public void Compress
{
;)"Console.WriteLine("Implementing the Compress Method
}
) (public void Decompress
{
;)"Console.WriteLine("Implementing the Decompress Method
}
-2-1-17
.
ICompressible ILoggedCompressible
.
interface ILoggedCompressible : ICompressible
{
;)(void LogSavedBytes
}
IloggedCompressible ICompressible
. ILoggedCompressible
299
09177112161 - -
C#
ICompressible ILoggedCompressible .
.
-3-1-17
.
. IStorableCompressible
.
interface IStorableCompressible : IStorable, ILoggedCompressible
{
void LogOriginalSize();
}
. :2-17
2-17
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace ExtendAndCombineInterface
{
interface IStorable
{
void Read( );
void Write( object obj );
int Status { get; set; }
}
// here's the new interface
interface ICompressible
{
void Compress( );
void Decompress( );
}
// Extend the interface
interface ILoggedCompressible : ICompressible
{
void LogSavedBytes( );
}
// Combine Interfaces
interface IStorableCompressible : IStorable, ILoggedCompressible
{
void LogOriginalSize( );
}
// yet another interface
interface IEncryptable
{
void Encrypt( );
void Decrypt( );
}
public class Document : IStorableCompressible, IEncryptable
{
// hold the data for IStorable's Status property
private int status = ;
// the document constructor
public Document( string s )
{
Console.WriteLine( "Creating document with: {}", s );
}
// implement IStorable
300
public void Read( )
{
Console.WriteLine(
"Implementing the Read Method for IStorable" );
}
public void Write( object o )
{
Console.WriteLine(
"Implementing the Write Method for IStorable" );
}
public int Status
{
get
{
return status;
}
set
{
status = value;
}
}
// implement ICompressible
public void Compress( )
{
Console.WriteLine( "Implementing Compress" );
}
public void Decompress( )
{
Console.WriteLine( "Implementing Decompress" );
}
// implement ILoggedCompressible
public void LogSavedBytes( )
{
Console.WriteLine( "Implementing LogSavedBytes" );
}
// implement IStorableCompressible
public void LogOriginalSize( )
{
Console.WriteLine( "Implementing LogOriginalSize" );
}
// implement IEncryptable
public void Encrypt( )
{
Console.WriteLine( "Implementing Encrypt" );
}
public void Decrypt( )
{
Console.WriteLine( "Implementing Decrypt" );
}
}
public class Tester
{
static void Main( )
{
// create a document object
Document doc = new Document( "Test Document" );
// cast the document to the various interfaces
IStorable isDoc = doc as IStorable;
if ( isDoc != null )
{
isDoc.Read( );
}
else
Console.WriteLine( "IStorable not supported" );
ICompressible icDoc = doc as ICompressible;
301
09177112161 - -
C#
if ( icDoc != null )
{
icDoc.Compress( );
}
else
Console.WriteLine( "Compressible not supported" );
ILoggedCompressible ilcDoc = doc as ILoggedCompressible;
if ( ilcDoc != null )
{
ilcDoc.LogSavedBytes( );
ilcDoc.Compress( );
// ilcDoc.Read( );
}
else
Console.WriteLine( "LoggedCompressible not supported" );
IStorableCompressible isc = doc as IStorableCompressible;
if ( isc != null )
{
isc.LogOriginalSize( ); // IStorableCompressible
isc.LogSavedBytes( ); // ILoggedCompressible
isc.Compress( ); // ICompressible
isc.Read( ); // IStorable
}
else
{
Console.WriteLine( "StorableCompressible not supported" );
}
IEncryptable ie = doc as IEncryptable;
if ( ie != null )
{
ie.Encrypt( );
}
else
Console.WriteLine( "Encryptable not supported" );
}
}
}
Output:
Creating document with: Test Document
Implementing the Read Method for IStorable
Implementing Compress
Implementing LogSavedBytes
Implementing Compress
Implementing LogOriginalSize
Implementing LogSavedBytes
Implementing Compress
Implementing the Read Method for IStorable
Implementing Encrypt
302
as
null .
;ICompressible icDoc = doc as ICompressible
) if ( icDoc != null
{
;) (icDoc.Compress
}
else
;) "Console.WriteLine( "Compressible not supported
.
;ILoggedCompressible icDoc=doc as ILoggedCompressible
-2-17
IStorable Document:
;)"Document doc = new Document("Test Document
;doc.status = -
;)(doc.Read
Document
.
;IStorable isDoc = doc
;isDoc.status =
;) (isDoc.Read
Document IStorable .
. :
;)(IStorable isDoc = new IStorable
:
;)"Document doc = new Document("Test Document
.
;IStorable isDoc = doc
.
;)"IStorable isDoc = new Document("Test Document
.
.
.
-1-2-17
.
IStorable ICompressible
.
;]Document doc = myCollection[
;IStorable isDoc = (IStorable) doc
;) (isDoc.Read
303
09177112161 - -
C#
: IStorable Document
public class Document : IStorable
. ICompressible ICompressible
.
An exception of type System.InvalidCastException was thrown.
is -2-2-17
#C .
. is . is .
expression is type
304
// IStorable.Status
public int Status
{
get
{
return status;
}
set
{
status = value;
}
}
}
// derives from Document and implements ICompressible
public class CompressibleDocument : Document, ICompressible
{
public CompressibleDocument(String s) :
base(s)
{ }
public void Compress( )
{
Console.WriteLine("Compressing...");
}
public void Decompress( )
{
Console.WriteLine("Decompressing...");
}
}
public class Tester
{
static void Main( )
{
// A collection of Documents
Document[] docArray = new Document[];
// First entry is a Document
docArray[] = new Document( "Test Document" );
// Second entry is a CompressibleDocument (ok because
// CompressibleDocument is a Document)
docArray[] =
new CompressibleDocument("Test compressibleDocument");
// don't know what we'll pull out of this hat
foreach (Document doc in docArray)
{
// report your name
Console.WriteLine("Got: {}", doc);
// Both pass this test
if (doc is IStorable)
{
IStorable isDoc = (IStorable)doc;
isDoc.Read( );
}
// fails for Document
// passes for CompressibleDocument
if (doc is ICompressible)
{
ICompressible icDoc = (ICompressible)doc;
icDoc.Compress( );
}
}
}
}
}
Output:
Creating document with: Test Document
Creating document with: Test compressibleDocument
305
09177112161 - -
C#
Got: IsOperator.Document
Reading...
Got: IsOperator.CompressibleDocument
Reading...
Compressing...
. if )( Main
if (doc is IStorable)
. if .
. Document
if (doc is ICompressible)
. CompressibleDocument
ICompressible .
. is . ICompressible Document
as -3-2-17
. is as
. null as .
. as
. as .
. as
expression as type
. null as 3-17
static void Main()
{
// A collection of Documents
Document[] docArray = new Document[];
// First entry is a Document
docArray[] = new Document( "Test Document" );
// Second entry is a CompressibleDocument (ok because
// CompressibleDocument is a Document)
docArray[] = new CompressibleDocument("Test compressibleDocument");
// don't know what we'll pull out of this hat
foreach (Document doc in docArray)
{
// report your name
Console.WriteLine("Got: {}", doc);
// Both pass this test
IStorable isDoc = doc as IStorable;
if (isDoc != null)
{
isDoc.Read( );
}
// fails for Document
// passes for CompressibleDocument
ICompressible icDoc = doc as ICompressible;
if (icDoc != null)
{
icDoc.Compress( );
}
}
306
-4-2-17 as is
as .
is .
-5-2-17
. IStorable
.
abstract class Storable
{
;)(abstract public void Read
;) (abstract public void Write
}
override-3-17
.
override .
Document IStorable ()Read ()Write virtual
. Document ()Read ()Write
Document .
4-17 3-17 override . ()Read
virtual ()Document.Read Note
override Document.
4-17
#region Using directives
;using System
;using System.Collections.Generic
;using System.Text
307
09177112161 - #endregion
namespace overridingInterface
{
interface IStorable
{
void Read( );
void Write( );
}
// Simplify Document to implement only IStorable
public class Document : IStorable
{
// the document constructor
public Document( string s )
{
Console.WriteLine(
"Creating document with: {}", s );
}
// Make read virtual
public virtual void Read( )
{
Console.WriteLine(
"Document Read Method for IStorable" );
}
// NB: Not virtual!
public void Write( )
{
Console.WriteLine(
"Document Write Method for IStorable" );
}
}
// Derive from Document
public class Note : Document
{
public Note( string s ):
base(s)
{
Console.WriteLine(
"Creating note with: {}", s );
}
// override the Read method
public override void Read( )
{
Console.WriteLine(
"Overriding the Read method for Note!" );
}
// implement my own Write method
public new void Write( )
{
Console.WriteLine(
"Implementing the Write method for Note!" );
}
}
public class Tester
{
static void Main( )
{
// create a document reference to a Note object
Document theNote = new Note( "Test Note" );
IStorable isNote = theNote as IStorable;
if ( isNote != null )
{
isNote.Read( );
isNote.Write( );
}
Console.WriteLine( "\n" );
308
C#
. Document
;("Document theNote = new Note("Test Note
: IStorable Document as
IStorable isNote = theNote as IStorable;
C#
- 09177112161 -
-4-17
. . .
. 5-17 IStorable
ITalk . ()Read ITalk . ()Read
IStorable .
()Read ) ( Document
. .
)(void ITalk.Read
.
.
) (public void Talk
.
.
) (void ITalk.Read
public.
override virtual abstract new
. .
IStorable.
;) (theDoc.Read
.
;ITalk itDoc = theDoc
;)(itDoc.Read
5-17 .
5-17
#region Using directives
;using System
;using System.Collections.Generic
;using System.Text
#endregion
namespace ExplicitImplementation
{
interface IStorable
{
;) (void Read
;) (void Write
310
}
interface ITalk
{
void Talk( );
void Read( );
}
// Modify Document to implement IStorable and ITalk
public class Document : IStorable, ITalk
{
// the document constructor
public Document( string s )
{
Console.WriteLine( "Creating document with: {}", s );
}
// Make read virtual
public virtual void Read( )
{
Console.WriteLine( "Implementing IStorable.Read" );
}
public void Write( )
{
Console.WriteLine( "Implementing IStorable.Write" );
}
void ITalk.Read( )
{
Console.WriteLine( "Implementing ITalk.Read" );
}
public void Talk( )
{
Console.WriteLine( "Implementing ITalk.Talk" );
}
}
public class Tester
{
static void Main( )
{
// create a document object
Document theDoc = new Document( "Test Document" );
IStorable isDoc = theDoc;
isDoc.Read( );
ITalk itDoc = theDoc;
itDoc.Read( );
theDoc.Read( );
theDoc.Talk( );
}
}
}
Output:
Creating document with: Test Document
Implementing IStorable.Read
Implementing ITalk.Read
Implementing IStorable.Read
Implementing ITalk.Talk
-1-4-17
.
Document .
Document )( Read() , Write . IStorable
.
. IStorable Document API .
IStorable
311
C#
- 09177112161 -
: virtual
. Note Document ()ITalk.Read .
-2-4-17
. IBase P
.
interface IBase
{
} ;int P { get; set
}
IDerived P ()P .
interface IDerived : IBase
{
;)(new int P
}
.
. .
-3-4-17
.
. .
.
.
.
312
IStorable 6-17 .
.
6-17
using System;
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace ReferencesOnValueTypes
{
// declare a simple interface
interface IStorable
{
void Read( );
int Status { get;set;}
}
// Implement through a struct
public struct myStruct : IStorable
{
public void Read( )
{
Console.WriteLine(
"Implementing IStorable.Read" );
}
public int Status
{
get
{
return status;
}
set
{
status = value;
}
}
private int status;
}
public class Tester
{
static void Main( )
{
// create a myStruct object
myStruct theStruct = new myStruct( );
theStruct.Status = -; // initialize
Console.WriteLine(
"theStruct.Status: {}", theStruct.Status );
// Change the value
theStruct.Status = ;
Console.WriteLine( "Changed object." );
Console.WriteLine(
"theStruct.Status: {}", theStruct.Status );
// cast to an IStorable
// implicit box to a reference type
IStorable isTemp = ( IStorable ) theStruct;
// set the value through the interface reference
isTemp.Status = ;
Console.WriteLine( "Changed interface." );
Console.WriteLine( "theStruct.Status: {}, isTemp: {}",
theStruct.Status, isTemp.Status );
// Change the value again
theStruct.Status = ;
313
C#
Tester . -1 .
Status .
:
theStruct.Status: -
Status . .
Changed object.
theStruct.Status:
. IStorable .
theStruct . Status 4 .
:
Changed interface.
theStruct.Status: , isTemp:
.
.
.
Changed object.
theStruct.Status: , isTemp:
-5-17
.
. public.
314
as is .
. as null.
. IStorable
.
315
:
-
.
. .
.
.
. .
.
:
. .
-1-18
1 .
. .
.
. . .
Delegate
-1-1-18
.
.
. .
API
. .
.
: API .
. NET. API .
. :
StopFolding(); // Folding and shaping machine
FinishWelding(); // Welding machine
PaintOff(); // Painting machine
-2-1-18
:
class Controller
{
...
)(public void ShutDown
{
;)(folder.StopFolding
;)(welder.FinishWelding
;)(painter.PaintOff
}
...
// Fields representing the different machines
;private FoldingMachine folder
;private WeldingMachine welder
;private PaintingMachine painter
}
.
. Controller .
-3-1-18
.
. .
;)(void methodName
.
. :
;)(delegate void stopMachineryDelegate
delegate .
317
C#
- 09177112161 -
.
.
= + .
Controller .
class Controller
{
;)(delegate void stopMachineryDelegate
...
)(public Controller
{
;this.stopMachinery += folder.StopFolding
}
...
private stopMachineryDelegate stopMachinery; // Create an instance of the delegate
}
. . overload +
.
. = + .
. new
:
;)this.stopMachinery = new stopMachineryDelegate(folder.stopFolding
.
)(public void ShutDown
{
;)(this.stopMachinery
...
}
:
NullRefrencException .
. = +
.
)(public Controller
{
;this.stopMachinery += folder.StopFolding
;this.stopMachinery += welder.FinishWelding
;this.stopMachinery += painter.PaintOff
}
318
. Controller
. .
:
public .
;public stopMachineryDelegate stopMachinery
private .
public .
;)(public delegate void stopMachineryDelegate
...
public stopMachineryDelegate StopMachinery
{
get
{
;return this.stopMachinery
}
set
{
;this.stopMachinery = value
}
}
Remove/ Add .
Controller .
Control .
;)(Controller control = new Controller
;)(FoldingMachine folder = new FoldingMachine
;)(WeldingMachine welder = new WeldingMachine
;)(PaintingMachine painter = new PaintingMachine
...
;)control.Add(folder.StopFolding
;)control.Add(welder.FinishWelding
;)control.Add(painter.PaintOff
...
;)(control.ShutDown
...
-4-1-18
.
StopFolding Folder stopMachinery .
:
;this.stopMachinery += folder.StopFolding
319
C#
- 09177112161 -
.
StopFolding .
void StopFolding(int shutDownTime); // Shut down within the
specified number of seconds
FinishWelding PaintOff .
.
StopFolding .
:
)(void FinishFolding
{
folder.StopFolding(); // Shutdown immediately
}
: FinishFolding .
.
.
StopFolding #C .
.
. . .
. FinishFolding .
StopFolding .
. }{ delegate .
StopFolding StopMachinery .
;} ;)this.stopMachinery += delegate { folder.StopFolding(
FinishFolding.
. :
;) } ;)control.Add(delegate { folder.StopFolding(
}{ delegate . :
control.Add(delegate(int param, string param) { /* code that uses param
;)} and param ...
.
.
320
= - .
. .
#C .
.
.
.
1 . .
.
.
: StopMachinery )
( . .NET
.
NET. .
-2-18
.
.
.
.
. 3 .
) (.
. .
event .
: StopMachineryDelegate .
TemperatureMonitor .
class TemperatureMonitor
{
;)(public delegate void StopMachineryDelegate
...
}
Captured
Trap
Subscriber
321
C#
- 09177112161 -
MachineOverheating StopMachineryDelegate .
class TemperatureMonitor
{
;)(public delegate void StopMachineryDelegate
;public event StopMachineryDelegate MachineOverheating
...
}
TemperatureMonitor MachineOverheating .
.
.
-1-2-18
= + . = + .
MachineOverheating
.
;)(= new TemperatureMonitor
;} )+= delegate { folder.StopFolding(
;+= welder.FinishWelding
;+= painter.PaintOff
TemperatureMonitor tempMonitor
...
tempMonitor.MachineOverheating
tempMonitor.MachineOverheating
tempMonitor.MachineOverheating
.
. tempMonitor.MachineOverheating
.
-2-2-18
= + .
= - . = -
. .
-3-2-18
.
. tempretuerMonitor
Notify MachineryOverheating .
class TemperatureMonitor
{
;public delegate void StopMachinerDelegate
;public event StopMachineryDelegate MachineOverheating
...
)(private void Notify
{
)if (this.MachineOverheating != null
{
;)(this.MachineOverheating
}
}
...
}
322
. null null
= + null . null .
NullReferenceException .
.
-3-18 GUI
.NET GUI
. Button Control . Click EventHandler
. . EventHandler .
EventArgs .
namespace System
{
; )public delegate void EventHandler(object sender, EventArgs args
public class EventArgs
{
...
}
}
namespace System.Windows.Forms
{
public class Control :
{
;public event EventHandler Click
...
}
public class Button : Control
{
...
}
Button Click .
.
okay okay_Click Click okay okay_Click
.
class Example : System.Windows.Forms.Form
{
;private System.Windows.Forms.Button okay
...
)(public Example
{
;)(this.okay = new System.Windows.Forms.Button
;)this.okay.Click += new System.EventHandler(this.okay_Click
...
}
)private void okay_Click(object sender, System.EventsArgs args
{
// Your code to handle the Click event
}
}
323
C#
- 09177112161 -
: .
.
;)this.okay.Click += new System.EventHandler (this.okay_Click
;this.okay.Click += this.okay_Click
2005VS . GUI
. void
. EventArgs.
sender .
sender .
Click . sender
.
delegate
.
;)(delegate void stopMachineryDelegate
:
;private stopMachineryDelegate stopMachinery
;()stopMachinery
.
;)this.stopMachinery = new stopMachineryDelegate(folder.stopFolding
event .
;)(public delegate void StopMachineryDelegate
;public event StopMachineryDelegate MachineOverheating
= +
.
;tempMonitor.MachineOverheating += welder.FinishWelding
= + = - .
event null.
324
try/catch/finally / .
NET. .
-1-19
. .
) (FCL .
NET. ) 1(SEH
.
. NET.
.
SEH
:
.
.
CLR .
.
.
.
Structured exception handling
C#
- 09177112161 -
. NET.
.
.
. . NET. System.Exception .
.
-2-19 System.Exception
1-19 System.Exception .
SystemException ApplicationException .
)NET. IOException ( ArithmticException
SystemException ApplicationException
. .
System.Exception .
1-19
System.Exception . 1-19 .
1-19
HelpLink
String
InnerException
Exception
Message
String
Source
String
StackTrace
String
URL .
null
. GetBaseException
.
. .
TargetSite
MethodBase .
.
326
DeclaringType
.
HResult
Int32
Com
. Com
HResult
.
-3-19
#C try/catch/finally ) (2-19 .
catch
. catch
catch
.
. .
2-19
try
Catch finally
. try catch finally
catch
327
C#
- 09177112161 -
Catch catch
. .
.
. .
{..} Exception
)ex
System.DivideByZeroException . ex
. ex.Message ex.StackTrace
catch . .
.
.
{..} ( Catch(Divide By zero Exception
ex
ex
ex
. )
( Exception System.Exception .
catch .
finally .
: catch throw
. throw
throw .
.
finally
. finally .
. .
catch .
System.Exception
Listing 4-2u
;using System
// Class to illustrate results of division by zero
public class TestExcep
{
328
)public static int Calc(int j
{
;)return ( / j
}
}
class MyApp
{
)(public static void Main
{
;)(TestExcep exTest = new TestExcep
try
{
// Create divide by zero in called method
;)int dZero = TestExcep.Calc(
// This statement is not executed
;)Console.WriteLine("Result: {}",dZero
}
)catch(DivideByZeroException ex
{
;)Console.WriteLine("{}\n{}\n", ex.Message, ex.Source
;))(Console.WriteLine(ex.TargetSite.ToString
;)Console.WriteLine(ex.StackTrace
}
)catch (Exception ex
{
;)Console.WriteLine("General "+ex.Message
}
finally
{
;)"Console.WriteLine("Cleanup occurs here.
}
}
}
TestExcep.Calc
. Calc
Calc MyApp
DivideByZeroException . catch
.
Ex.Message
Ex.Source
Zeroexcept
ex.TargetSite
()void Main
ex.StackTrace
-4-19
.
329
09177112161 - -
C#
.
. .
. 2-19
. NoDescException
2-19
// Custom Exception Class
[Serializable]
public class NoDescException : ApplicationException
{ // Three constructors should be implemented
public NoDescException(){}
public NoDescException(string message):base(message){}
public NoDescException(string message, Exception innerEx)
:base(message, innerEx){ }
}
// Interfaces that shape objects are to implement
public interface IShapeFunction
{ double GetArea(); }
public interface IShapeDescription
{ string ShowMe();}
// Circle and Rectangle classes are defined
class Circle : IShapeFunction
{
private double radius;
public Circle (double rad)
{
radius= rad;
}
// Methods to implement both interfaces
public double GetArea()
{ return (*
*radius*radius); }
}
class Rectangle : IShapeFunction, IShapeDescription
{
private int width, height;
public Rectangle(int w, int h)
{
width= w;
height=h;
}
// Methods to implement both interfaces
public double GetArea()
{ return (height*width); }
public string ShowMe()
{ return("rectangle"); }
}
public class ObjAreas
{
public static void ShowAreas(object ObjShape)
{
// Check to see if interfaces are implemented
if (!(ObjShape is IShapeDescription &&
ObjShape is IShapeFunction) )
{
// Throw custom exception
string objName = ObjShape.ToString();
throw new NoDescException
("Interface not implemented for "+objName);
}
// Continue processing since interfaces exist
IShapeFunction myShape = (IShapeFunction)ObjShape;
330
;IShapeDescription myDesc = (IShapeDescription) ObjShape
;)(string desc = myDesc.ShowMe
Console.WriteLine(desc+" Area= "+
;))(myShape.GetArea().ToString
}
}
shape
ObjAreas.ShowAreas .
static ObjAreas.ShowAreas method.
)Circle myCircle = new Circle(4,0
;)4,0
)Rectangle myRect = new Rectangle(52
;)52
try
{
;)ObjAreas.ShowAreas(myRect
;)ObjAreas.ShowAreas(myCircle
}
)catch (NoDescException ex
{
;)Console.WriteLine(ex.Message
}
ShowAreas .
NoDescException
. Circle .
NoDescException .
:
ApplicationException .
Exception . Exception
.
-1 .
-2 Message.
-3 Exception
.
+ base .
.
+ serializable . xml
.
.
331
C#
- 09177112161 -
-5-19
CLR catch .
CLR .
. NET
.
.
332
#C
:
:1 .NET 16 .
.
2 .
:String .NET .
.
:String .NET .
:StringBuilder .
: Regex .NET
.
.NET .
String . String.Format
.
JIT .
-1-20
. 128
. ANSI .
.
Unicode
Localization
C#
- 09177112161 -
.
. PlatForm
.
-1-1-20
.NET . 16
. 65535 .
1-20 .
1-20
128 .
75 . .
310 56609 .
. 96382
. 130
OCR .
16 100000
. 16 . 1
. 32 16 . 100000
.
.
16 32 API .NET
.
. . .NET .
: .
ttfext.exe .
.
Surrogate
334
#C
-2-1-20
.NET char Char . char
. .
char
char . char
. .
;"string klm = "KLM
;byte b = 75
;char k
// Different ways to assign 'K' to variable K
;'k = 'K
k = klm[0]; // Assign "K" from first value in klm
k = (char) 75; // Cast decimal
k = (char) b; // cast byte
k = Convert.ToChar(75); // Converts value to a char
Char
.
Convert . char
1 GetNumericValve .
// '7' has Unicode value of 55
;'char k = '7
int n = (int) k; // n = 55
n = (int) char.GetNumericValue(k); // n = 7
-3-1-20
.NET
.
.
2004 9May 2004/9/5 CLR .
.
.NET CultureInfo /
.
Char.ToUpper .
// Include the System.Globalization namespace
// Using CultureInfo Azerbaijan
;'char i = 'i
// Second parameter is false to use default culture settings
// associated with selected culture
;) CultureInfo myCI = new CultureInfo("az", false
;)i = Char.ToUpper(i,myCI
Linguistic
335
C#
- 09177112161 -
-4-1-20
30 .NET . UnicodeCategory
()Char.GetUnicodeCategory .
:
;'Char k = 'K
int iCat = (int) char.GetUnicodeCategory(k); // 0
Console.WriteLine(char.GetUnicodeCategory(k)); // UppercaseLetter
;char cr = (Char)13
iCat = (int) char.GetUnicodeCategory(cr); // 14
Console.WriteLine(char.GetUnicodeCategory(cr)); // Control
K UpperCaseLetter Control
char . .
GetUnicodeCategory false true . 1-20
.
5-1
IsControl
F007U+
000U+ F001U+
U+0080 U+009F.
IsDigit
IsLetter
IsLetterorDigit
IsLower
8
0124
018
1
0 9
336
#C
IsUpper
IsPunctuation
)DashPunctuation(19
OpenPunctuation(20),
OtherPunctuation(24).
IsSeparator
111213
IsSurrogate
IsSymbol
IsWhiteSpace
16
252628
11
20X0 .
) ( ) D0X0 (
(tab 09X0( ) A0X0 (
) C0X0 (
(tab0X0
B(
. OverLoad
.
Console.WriteLine(Char.IsSymbol('+')); // true
Console.WriteLine(Char.IsPunctuation('+')): // false
;"string str = "black magic
Console.WriteLine(Char.IsWhiteSpace(str, 5)); // true
;'char p = '.
Console.WriteLine(Char.IsPunctuation(p)); // true
Int iCat = (int) char.GetUnicodeCategory(p); // 24
;'(' = Char p
Console.WriteLine(Char.IsPunctuation(p)); // true
int iCat = (int) char.GetUnicodeCategory(p); // 20
-2-20
. .
-1-2-20
string .
.
. .NET
.
337
C#
- 09177112161 -
-2-2-20 1
.
Stack . Heap . CLR
2
. . .
;""Kubla Khan
;""Kubla Khan
String.Copy(poem2); // Create new string object
;""Christabel
=
=
=
=
poem1
poem2
poem3
poem4
string
string
string
string
2-20 .
2-20
hash . hash
heap . JIT
Kubla Khan heap
. (2Kubla Khan (poem CLR
2poem ) (1poem .
. String.Copy 3Poem .
heap . 4poem
.
.
)==( Object.ReferenceEqual
.
Console.WriteLine(poem1 == poem2); // true
Console.WriteLine(poem1 == poem3); // true
Console.WriteLine(ReferenceEquals(poem1, poem3)); // false
Console.WriteLine(ReferenceEquals(poem1,
"Kubla Khan")); // true
338
Interning
Intern Pool
#C
true .
3poem 2poem . heap false .
.NET .
. String.Intern
.
;"string khan = " Khan
;string poem5 = "Kubla" + khan
Console.WriteLine(ReferenceEquals(poem5, poem1)); // false
// Place the contents of poem5 in the intern poolif not there
;)poem5 = String.Intern(poem5
Console.WriteLine(ReferenceEquals(poem5, poem1)); // true
-3-2-20
System.String OverLoad .
4 .
: String.Equals String.Compare String.CompareOrdinal
. ) (
.
:
.
:
.
.
.
-3-20
.
ReferenceEquals .
.
.
.NET Equals
. .
339
09177112161 - -
C#
. Equals
string poem1 = "Kubla Khan";
string poem2 = "Kubla Khan";
string poem3 = String.Copy(poem2);
string poem4 = "kubla khan";
//
Console.WriteLine(String.Equals(poem1,poem2)); // true
Console.WriteLine(poem1.Equals(poem3)); // true
Console.WriteLine(poem1 == poem3); // equivalent to Equals
Console.WriteLine(poem1 == poem4); // false case differs
.( . Equals ) ==
OverLoad Equals
. String Compare .
String.Compare -1-3-20
String.Compare
. OverLoad .
:
int Compare (string str1, string str2)
Compare (string str1, string str2, bool IgnoreCase)
Compare (string str1, string str2, bool IgnoreCase,
CultureInfo ci)
Compare (string str1, int index1, string str2, int index2,
int len)
. : Str2, Str1
. false . true :IgnoreCase
Str2 Str1 :index1, index2
. CultureInfo :C2
.)( Compare
. .
.
. Compare
int result;
string stringUpper = "AUTUMN";
string stringLower = "autumn";
// (1) Lexical comparison: "A" is greater than "a"
result = string.Compare(stringUpper,stringLower); // 1
// (2) IgnoreCase set to false
result = string.Compare(stringUpper,stringLower,false); // 1
// (3)Perform case-insensitive comparison
result = string.Compare(stringUpper,stringLower,true); // 0
340
#C
.NET .
. Compare CLR
. US
.
.
.
Compare
Thread.CurrentThread.CurrentCulture .
CultureInfo . Germany
.
CultureInfo ci = new CultureInfo("de-DE"); // German culture
CultureInfo
CurrentCulture : InvariantCulture
.
()Compare .
using System.Globalization; // Required for CultureInfo
// Perform case-sensitive comparison for Czech culture
;"string s1 = "circle
;"string s2 = "chair
result = string.Compare(s1, s2,
true, CultureInfo.CurrentCulture)); // 1
result = string.Compare(s1, s2,
true, CultureInfo.InvariantCulture)); // 1
// Use the Czech culture
result = string.Compare(s1, s2,
true, new CultureInfo("cs-CZ")); // -1
Chair , Circle US
. .
Ch C .
CultureInfo
-2-3-20 String.CompareOrdinal
String.CompareOrdinal . .
. .
. Compare CompareOrdinal .
;"stringUpper = "AUTUMN
;"stringLower = "autumn
= string.Compare(stringUpper,stringLower,
CultureInfo.InvariantCulture); // 1
341
string
string
//
result
false,
C#
Compare .
CompareOrdinal . (0041A(U+ ()a0061U+
.
-4-20
String
.
-1-4-20
) ([String[n n
. String
IndexOf IndexOfAny . 2-20 .
2-20
] [n
16 n .
;Int ndx=0
(While (ndx<poem.length
}
Write (Poem[ndx
;([Console.
=;1Ndx+
{
IndexOf /LastIndexOf
.
-1 .
([[int
Poem=kubla khan
String
n=Poem.Index of (la);//3
of (h);//
Cont
IndexOfAny/LastIndex
OfAny
0n=Poem.Index
Index of (k,
Int
6);//4n=Poem
/
.
Poem=kubla khan
Vowels = new char [5
;String
[[Char
} u0, 2a, e,
;{,
342
#C
-2-4-20
16 .
32 . 16
. [Poem[ndx
.
String .NET
16 .
GetTextElementEnumerator .
.
= TextElementEnumerator tEnum
; )StringInfo.GetTextElementEnumerator(poem
while (tEnum.MoveNext()) // Step through the string
{
Console.WriteLine(tEnum.Current); // Print current char
}
()MoveNext Current .
-3-4-20
3-20 String .
.
3-20
(int, string
(Insert
.
;"string mariner = "and he stoppeth three
(string verse = mariner.Insert
;)"mariner.IndexOf(" three")," one of
"// verse --> "and he stoppeth one of three
PadLeft/PadRight
.
.
;"string rem = "and so on
;)rem =rem.PadRight(rem.Length+3,'.
"// rem --> "and so on...
(Remove(p,n
n p .
;"string verse = "It is an Ancient Mariner
;))string newverse = (verse.Remove(0,9
"// newverse --> "Ancient Mariner
(Replace(A,B
.
;String astring = nap ace sap. Path
343
09177112161 - -
C#
Char
([]Split(Char
.
string words = "red,blue orange ";
string [] split = words.Split(new Char []
{' ', ','});
Console.WriteLine(split[2]); // orange
()Toupper
(Toupper(CultureInfo
() Tolower
(Tolower(CultureInfo
[]Char .
([]Trim
(params Char
()Trim
.
String name= Samuel Coleridge;
Nam=name.Trim( );
Char
][( TrimEnd
null .
.
(params Char
TrimStart(params Char
([]
. n
. L L
(SubString
(Substring
(n
(n,l
()ToCharArray
(ToCharArray(n,l
.
. Insert Remove, Replace . StringBuilder
344
#C
-4-4-20
. :
. 8 .
. 1
2 .
.NET .
.
UTF-8
4 .
. 0800X0 FF07X0
0800x0 4 .
.NET 8UTF .
UTF16
2 ) ( . .
ASCII
8 . 00OX f7OX
.
System.Text Encoding .
. 8UTF ASCII
Unicode . 16UTF.
overload .
GetBytes : GetString
.
;"string text= "In Xanadu did Kubla Khan
;Encoding UTF8Encoder = Encoding.UTF8
;)byte[] textChars = UTF8Encoder.GetBytes(text
Console.WriteLine(textChars.Length); // 24
// Store using UTF-16
;)textChars = Encoding.Unicode.GetBytes(text
Console.WriteLine(textChars.Length); // 48
// Treat characters as two bytes
;)string decodedText = Encoding.Unicode.GetString(textChars
" Console.WriteLine(decodedText); // "In Xanadu did ...
345
Legacy
Third Party
C#
- 09177112161 -
. 8UTF-
.
;)(UTF8Encoding UTF8Encoder = new UTF8Encoding
ASCIIEncoding
. .
-5-20 StringBuilder
.
100 . 100
.
StringBuilder )(
.
. ()ToString .
1-20 StringBuilder .
1-20
;using System
;using System.Text
public class MyApp
)(static void Main
{
// Create comma delimited string with quotes around names
;" string namesF = "Jan Donna Kim
;"string namesM = "Rob James
;)(StringBuilder sbCSV = new StringBuilder
;)sbCSV.Append(namesF).Append(namesM
;)"'sbCSV.Replace(" ","',
// Insert quote at beginning and end of string
;)"'"(sbCSV.Insert(0,"'").Append
;)(string csv = sbCSV.ToString
'// csv = 'Jan','Donna','Kim','Rob','James
}
}
.
.
-1-5-20 StringBuilder
StringBuilder
.
)// Stringbuilder(initial value
;)"StringBuilder sb1 = new StringBuilder("abc
)// StringBuilder(initial value, initial capacity
;)StringBuilder sb2 = new StringBuilder("abc", 16
)// StringBuiler(Initial Capacity, maximum capacity
;)StringBuilder sb3 = new StringBuilder(32,128
StringBuilder .
Replace Insert Append Remove .
346
#C
int i = 4;
char[] ch = {'w','h','i','t','e'};
string myColor = " orange";
StringBuilder sb = new StringBuilder("red blue green");
sb.Insert(0, ch); // whitered blue green
sb.Insert(5," "); // white red blue green
sb.Insert(0,i); // 4white red blue green
sb.Remove(1IR); // 4 red blue green
sb.Append(myColor); // 4 red blue green orange
sb.Replace("blue","violet"); // 4 red violet green orange
string colors = sb.ToString();
StringBuilder -2-5-20
+ . StringBuilder 2-20
. . 50000 a
Environment.TickCount . StringBuilder.Append
.
2-20
using System.Text;
public class MyApp
static void Main()
{
Console.WriteLine("String routine");
string a = "a";
string str = string.Empty;
int istart, istop;
istart = Environment.TickCount;
Console.WriteLine("Start: "+istart);
// Use regular C# concatenation operator
for(int i=0; i<50000; i++)
{
str += a;
}
istop = Environment.TickCount;
Console.WriteLine("Stop: "+istop);
Console.WriteLine("Difference: " + (istop-istart));
// Perform concatenation with StringBuilder
Console.WriteLine("StringBuilder routine");
StringBuilder builder = new StringBuilder();
istart = Environment.TickCount;
Console.WriteLine("Start: "+istart);
for(int i=0; i<50000; i++)
{
builder.Append(a);
}
istop = Environment.TickCount;
str = builder.ToString();
Console.WriteLine("Stop: "+Environment.TickCount);
Console.WriteLine("Difference: "+ (istop-istart));
}
}
.
String routine
Start: 1422091687
Stop: 1422100046
Difference: 9359
347
C#
-6-20
String.Format .
.
CLR .
.
.
;)String s= String.Format("The square root of {0} is {1}.",64,8
// output: The square root of 64 is 8.
Overload . :
. Console.WriteLine
String.Format .
-1-6-20
3-20 String.Format .
.
3-20
.
}{ .
.1 .
.
.2 .
. .
348
#C
.3 .
ToString .NET .
.
-2-6-20
9
. .
#C . 4-20 .
4-20
}1458,75},2C:0
1458,75 $
.
. .-
.
}}, D:
}}, -D:
00455
00455-
.
. .
{:E},
{:E}, -
5.4783+E004
ddddE+nnm .
.
dddd.ddd
{:F},
{:F},
. .
.
.
003E+3,30
162
8162,57
{:G}, .
{:G},
{:G},
{:G},
9.9E-06
4.6E+02
456
783229.34
4-
.
. 1000
{:N},
{:N},
1,045.78
4RKV
.
.
.
{:P},
{:P},
78.00 %
78.650 %
.
.
.
{:R},
1.62736
.
.
. .
349
{:X},
{:X},
{:x},
19
001V
001f
C#
- 09177112161 -
. .
Console.Write Console.WriteLine .
Console.WriteLine("The Hex value of {0} is {0:X} ",31); //1F
ToString .
;decimal pct = .758M
Console.Write("The percent is "+pct.ToString("P2")); // 75.80 %
.NET . )# :
()0 (), () . () % ( ;) ( . .
decimal dVal = 2145.88M; // decimal values require M suffix
;string myFormat
myFormat = dVal.ToString("#####"); // 2146
myFormat = dVal.ToString("#,###.00"); // 2,145.88
;myFormat = String.Format("Value is {0:#,###.00
;)(#,###.00)}",-4567
)// semicolon specifies alternate formats. (4,567.00
;)myFormat = String.Format("Value is {0:$#,###.00}", 4567
// $4,567.00
Console.WriteLine("{0:##.00%}",.18); // 18.00 %
; . .
.
.
-3-6-20
DateTime .
. 5-20 .
5-5
2004/19/1
Monday, January
19, 2004
/ ) (
Monday, January
19, 2004 4:05 PM
/ ) (
Monday, January
19, 2004 4:05:20 PM
/ ) (
PM 4:05 2004/19/1
6:05 2004/1/19
/ ) (
PM 4:05:20 2004/19/1
16:05:20 2004/1/19
19,1,2004
Montag, 19
Januar,2004
Montag, 19
Januar, 2004
16:05
Montag, 19
Januar,2004
16:05:20
350
#C
m,M
y,Y
/ 8601Iso
January 19
Januar 19
January, 2004
Januar, 2004
PM 4:05
16:05
PM 4:05:20
16:05:20
16:05:20T 9-01-2004
19-01-2004
16:05:20T
. .
u
Z16:05:20 19-01-2004
Monday, January
192004 21:05:20 PM
19-01-2004
Z16:05:20
Montag, 19.
,Januar
21:05:20 2004
. DateTime
.
DateTime curDate = DateTime.Now; // Get Current Date
Console.Writeline("Date: {0:d} ", curDate); // 1/19/2004
// f: --> Monday, January 19, 2004 5:05 PM
;)Console.Writeline("Date: {0:f} ", curDate
// g: --> 1/19/2004 5:05 PM
;)Console.Writeline("Date: {0:g} ", curDate
. 6-20 .
6-20
. .
dd
. .
ddd
dddd
MM
MMM
MMMM
yy
. .
351
C#
09177112161 -yyyy
HH
24
mm
.
;DateTime curDate = DateTime.Now
;)f = String.Format("{0:dddd} {0:MMM} {0:dd}", curDate
// output: Monday Jan 19
)"f = currDate.ToString("dd MMM yyyy
// output: 19 Jan 2004
// The standard short date format (d) is equivalent to this:
Console.WriteLine(currDate.ToString("M/d/yyyy")); // 1/19/2004
Console.WriteLine(currDate.ToString("d")); // 1/19/2004
CultureInfo ci = new CultureInfo("de-DE"); // German
)f = currDate.ToString("dd-MMMM-yyyy HH:mm", ci
// output: 19-Januar-20MQ 23:07
ToString String.Format .
. .
-4-6-20
. .NET
. German
European .
) (/ 19Monday , January . Januar19Montag, .
ToString CultureInfo German .
CultureInfo ci = new CultureInfo("de-DE"); // German
;))Console.WriteLine(curDate.ToString("D",ci
// output ---> Montag, 19. Januar 2004
Console.WriteLine(curDate.ToString("dddd",ci)); // -->Montag
dddd .
DateTime.DayOfWeek .
DateTimeFormatInfo NumberFormatInfo
.
NumberFormatInfo
. DateTimeFormatInfo
. FullDateTimePattern
F .
NumberFormatInfo DateTimeFormatInfo
.NET .
override.
352
#C
.
.
>NumberFormatInfo.CurrentInfo.<property
>CultureInfo.CurrentCulture.NumberFormat.<property
CurrentInfo .
CultureInfo .
;)"CultureInfo ci = new CultureInfo("de-DE
;string f = ci.NumberFormat.CurrencySymbol
NumberFormatInfo DateTimeFormatInfo
. 3-20
3-20
using System
using System.Globalization
Class MyApp
// NumberFormatInfo
;string curSym = NumberFormatInfo.CurrentInfo.CurrencySymbol
;int dd = NumberFormatInfo.CurrentInfo.CurrencyDecimalDigits
;int pdd = NumberFormatInfo.CurrentInfo.PercentDecimalDigits
// --> curSym = "$" dd = 2 pdd = 2
// DateTimeFormatInfo
;string ldp= DateTimeFormatInfo.CurrentInfo.LongDatePattern
"// --> ldp = "dddd, MMMM, dd, yyyy
;]string enDay = DateTimeFormatInfo.CurrentInfo.DayNames[1
;]string month = DateTimeFormatInfo.CurrentInfo.MonthNames[1
;)"CultureInfo ci = new CultureInfo("de-DE
;]string deDay = ci.DateTimeFormat.DayNames[1
"// --> enDay = "Monday" month = February deDay = "Montag
// Change the default number of decimal places
// in a percentage
;decimal passRate = .840M
Console.Write(passRate.ToString("p",ci)); // 84,00%
;ci.NumberFormat.PercentDecimalDigits = 1
Console.Write(passRate.ToString("p",ci)); // 84,0%
}
NET. .
NumberFormatInfo DateTimeFormatInfo
NET. . .
-7-20
. 1960
SNOBOL . Grep Unix Grep .
. Grep Perl
NET. .
. Regex .
353
C#
- 09177112161 -
-1-7-20 Regex
Regex .
.
Regex System.Text.RegualarExpressions .
:
: Pattern
:Regex Options . :
-CultureInvariant .
IgnoreCase .
RightToLeft .
:
Regex r1 = new Regex(" "); // Regular expression is a blank
;)"String words[] = r1.Split("red blue orange yellow
"// Regular expression matches upper- or lowercase "at
;)Regex r2 = new Regex("at", RegexOptions.IgnoreCase
Regex . .
RegexOptions .
Regex
Regex . Match Split Replace IsMatch Matches
. Overload .
Regex .
.
.
Regex . .
.
()IsMatch
.
.
;"string searchStr = "He went that a way
;)"Regex myRegex = new Regex("at
// instance methods
bool match = myRegex.IsMatch(searchStr); // true
// Begin search at position 12 in the string
match = myRegex.IsMatch(searchStr,12); // false
354
#C
// Static Methods both return true
;)"match = Regex.IsMatch(searchStr,"at
;)match = Regex.IsMatch(searchStr,"AT",RegexOptions.IgnoreCase
()Replace
.
overload .
Count StartAt . .
MatchEvaluator .
.
.
;string newStr
newStr = Regex.Replace("soft rose","o","i"); // sift rise
// instance method
"Regex myRegex = new Regex("o"); // regex = "o
// Now specify that only one replacement may occur
newStr = myRegex.Replace("soft rose","i",1); // sift rose
()Split
. ()String.Split
.
:Input
:Count .
.
:Startat .
:Pattern .
.
. " "*[ ], .
.
355
C#
()Matches() , Match
. ()Match Match
()Matches ) MatchCollection ( .
Index
Groups
.
. Groups
.
Length
Success
true false.
Valve
NextMatch
Match .
. ) (.
)( .
;"string verse = "In Xanadu did Kubla Khan
string patt = ".an..."; // "." matches any character
;)Match verseMatch = Regex.Match(verse, patt
356
#C
Console.WriteLine(verseMatch.Value); // Xanadu
Console.WriteLine(verseMatch.Index); // 3
//
)string newPatt = "K(..)"; //contains group(..
;)Match kMatch = Regex.Match(verse, newPatt
{ )while (kMatch.Success
Console.Write(kMatch.Value); // -->Kub -->Kha
Console.Write(kMatch.Groups[1]); // -->ub -->ha
;)(kMatch = kMatch.NextMatch
}
NextMatch kMatch .
newPatt .
K Groups .
.
MatchCollection . Match
Regex.Matches Count . Item
. NextMatch .
;"string verse = "In Xanadu did Kubla Khan
;")String newpatt = "K(..
))foreach (Match kMatch in Regex.Matches(verse, newpatt
Console.Write(kMatch.Value); // -->Kub -->Kha
// Could also create explicit collection and work with it.
;)MatchCollection mc = Regex.Matches(verse, newpatt
Console.WriteLine(mc.Count); // 2
-2-7-20
Regex .
.
.
. Regex ).(www.regexlib.com
.
: . \ d 0 9 .
: . {3d{\ : \ d\d\d
.
: . {3d{\^ :
.
:Escape \ . \{
.
8-20 .
8-20
357
C#
- 09177112161 -
Te?n ten tn
. . Teen . .
}{n
n Te{2}n teen .
Ten teeen .
.
}{,n
.
}{n,m
A\+B A+B . +
. \ .
. +
\d
)\ ( d )\ (D \ d\d 55 .
\D
. ] [9-0 ] D\D\ -0 XX .
[98.
\w
. \ 19A_ w\w\w\w .
\W
\ W w\ . ] ($) W\W\W\ a- .
[_9-0zA-Z \ W ]^a-zA-
[_9-0Z .
\n \r
\t \v
\f
\s
\ s \ S A B C , \w\S\w\S\w
\S
.
. Space tab
.
)0(
|
][ 0 0 0
. a.c Abc .
.
abcc .
OR
enquiry in|en .
aeiou] u] . [d\D\] .
.
358
#C
.
] x ] 8aeiou .
][8 0 0 0
.
;)"bool iMatch = Regex.IsMatch("245-09-8444",@"\d\d\d-\d\d-\d\d\d\d
.
.
.
;)"}bool iMatch = Regex.IsMatch("245-09-8444",@"\d{3}-\d{2}-\d{4
.
. .
.
. .
9-20 8 $ .
.
"@"^\d{3}-\d{2}-\d{4}$
9-20
\A
\b \B
.
.
\z \Z
)\ (Z .
.
SSN .
. .
.
;"string ssn = "245-09-8444
;"string ssnPatt = @"^(\d{3})-(\d{2})-(\d{4})$
;)Match ssnMatch = Regex.Match(ssn, ssnPatt
359
C#
.
. ) . 4-20
(.
4-20
.
[]Match.Groups . .
1 2 .
.
><name .
.
;"string txt ="Monday Hi:88 Lo:56 Tuesday Hi:91 Lo:61
. .
.
;")string rgPatt = @"(?<day>[a-zA-Z]+)\s*(?<temps>Hi:\d+\s*Lo:\d+
MatchCollection mc = Regex.Matches(txt, rgPatt); //Get matches
)foreach(Match m in mc
Console.WriteLine("{0} {1}",
;)]"m.Groups["day"],m.Groups["temps
//Output: Monday Hi:88 Lo:56
// Tuesday Hi:91 Lo:61
: .
: . ) (an|in|on OR
(an|in|on:?) :
360
#C
.
.
.
. .
;"string speech = "Four score and and seven years
patt = @"(\b[a-zA-Z]+\b)\s\1"; // Match repeated words
;)MatchCollection mc = Regex.Matches(speech, patt
{ )foreach(Match m in mc
Console.WriteLine(m.Groups[1]); // --> and
}
. .
/
and and
)\ (b
@"(\b[a-zA-Z]+\b)\s
and and
\1
.
.
. < \ >k
:
;">patt = @"(?<word>\b[a-zA-Z]+\b)\s\k<word
-3-7-20
.
.
.
Replace
;"string userName = "Claudel, Camille
;) "userName = Regex.Replace( userName, @"(\w+),\s*(\w+)", "$2 $1
Console.WriteLine(userName); // Camille Claudel
1 2 . Replace
$ . 2 1
.
;"String myText = "98, 98.0, +98.0, +98
string numPatt = @"\d+"; // Integer
numPatt = @"(\d+\.?\d*)|(\.\d+)"; // Allow decimal
numPatt = @"([+-]?\d+\.?\d*)|([+-]?\.\d+)"; // Allow + or-
361
C#
- 09177112161 -
(|) OR .
.
8 . .
null .
4 CaptureCollection .
;"string hex = "00AA001CFF0C
;"*)}string hexPatt = @"^(?<hex4>[a-fA-F\d]{4
;)Match hexMatch = Regex.Match(hex,hexPatt
Console.WriteLine(hexMatch.Value); // --> 00AA001CFFOC
;CaptureCollection cc = hexMatch.Groups["hex4"].Captures
)foreach (Capture c in cc
Console.Write(c.Value); // --> 00AA 001C FF0C
5-20
-8-20
7 ASCII ANSI .
90000 . NET.
16 .
NET. .
String.Format .
StringBuilder
.
Regex .
362
.
NET. .
System.IO.
-1-21
1 -21 . ] [ .
1-21
C#
09177112161 -1
: System.MarshalByRefObject NET.
.
: FileSystemInfo .
File :FileInfo .
:DirectoryInfo,Directry .
:Path .
:DriveInfo
-1-1-21 NET.
.
.
Directory :File .
.
.
:FileInfo, DirectoryIfo Directory File
public . .
.
.
.
.
FileInfo DirectoryInfo
Directory File ) ( . :
;)"FileInfo myFile = new FileInfo(@"C:\Program Files\My Program\ReadMe.txt
;)"myFile.CopyTo(@"D:\Copies\ReadMe.txt
:
;)"File.Copy(@"C:\Program Files\My Program\ReadMe.txt", @"D:\Copies\ReadMe.txt
. FileInfo
. .
FileInfo DirectoryInfo
. :
;)"DirectoryInfo myFolder = new DirectoryInfo(@"C:\Program Files
. Exists .
;)"FileInfo test = new FileInfo(@"C:\Windows
Marshaling
364
;))(Console.WriteLine(test.Exists.ToString
CreateTime
) DirectoryName (FileInfo
) Parent (DirectoryInfo
Exists
Extension
FullName
LastAccessTime
LastWriteTime
Name
) Root (DirectoryInfo
) Length (FileInfo
()Create
. FileInfo
Stream .
()Delete
.
.
()MoveTo
) ()CopyTo . .
(FileInfo
) ()GetDirectories
DirectoryInfo
(DirectoryInfo
)()GetFiles FileInfo
365
C#
- 09177112161 -
(DirectoryInfo
: .
.
FileInfo )( ()Create OpenWrite() OpenText() OpenRead() Open
()CreateText Stream .
.
// displays the creation time of a file,
// then changes it and displays it again
;)"FileInfo test = new FileInfo(@"C:\MyFile.txt
;))(Console.WriteLine(test.Exists.ToString
;))(Console.WriteLine(test.CreationTime.ToString
;)test.CreationTime = new DateTime(, , , , ,
;))(Console.WriteLine(test.CreationTime.ToString
.
True
// :: PM
// :: AM
.
.
-2-1-21 Path
Path .
. . Readme.txt
c:\MyDocuments . :
;))"Console.WriteLine(Path.Combine(@"C:\My Documents", "ReadMe.txt
Path Path
. Net.
366
: Display
.
ListBox . 34-2 FileProperties .
34-2
Up
. 34-2 My Dcumants .
ListBox . . 34
3 . 34-3
:
DirectoeyInfo
367
09177112161 - -
C#
. System.IO
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
System.IO;
.
partial class Form : Form
{
private string currentFolderPath;
: .
. Display
Files
. Folders
. Up
.)( ClearAllFields
.
protected void ClearAllFields()
{
listBoxFolders.Items.Clear();
listBoxFiles.Items.Clear();
textBoxFolder.Text = "";
textBoxFileName.Text = "";
textBoxCreationTime.Text = "";
textBoxLastAccessTime.Text = "";
textBoxLastWriteTime.Text = "";
textBoxFileSize.Text = "";
}
.)( DisplayFileInfo
.( )
protected void DisplayFileInfo(string fileFullName)
{
FileInfo theFile = new FileInfo(fileFullName);
if (!theFile.Exists)
throw new FileNotFoundException("File not found: " + fileFullName);
textBoxFileName.Text = theFile.Name;
textBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();
textBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();
textBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();
textBoxFileSize.Text = theFile.Length.ToString() + " bytes";
}
368
. ()DisplayFolderList .
.
protected void DisplayFolderList(string folderFullName)
{
DirectoryInfo theFolder = new DirectoryInfo(folderFullName);
if (!theFolder.Exists)
throw new DirectoryNotFoundException("Folder not found: " + folderFullName);
ClearAllFields();
textBoxFolder.Text = theFolder.FullName;
currentFolderPath = theFolder.FullName;
// list all subfolders in folder
foreach(DirectoryInfo nextFolder in theFolder.GetDirectories())
listBoxFolders.Items.Add(nextFolder.Name);
// list all files in folder
foreach(FileInfo nextFile in theFolder.GetFiles())
listBoxFiles.Items.Add(nextFile.Name);
}
. Display .
.
.
protected void OnDisplayButtonClick(object sender, EventArgs e)
{
try
{
string folderPath = textBoxInput.Text;
DirectoryInfo theFolder = new DirectoryInfo(folderPath);
if (theFolder.Exists)
{
DisplayFolderList(theFolder.FullName);
return;
}
FileInfo theFile = new FileInfo(folderPath);
if (theFile.Exists)
{
DisplayFolderList(theFile.Directory.FullName);
int index = listBoxFiles.Items.IndexOf(theFile.Name);
listBoxFiles.SetSelected(index, true);
return;
}
throw new FileNotFoundException("There is no file or folder with "
+ "this name: " + textBoxInput.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
FileInfo DirectoryInfo
. . Exist
.
) Files
.)( DisplayFileInfo .(
protected void OnListBoxFilesSelected(object sender, EventArgs e)
{
369
09177112161 - -
C#
try
{
string selectedString = listBoxFiles.SelectedItem.ToString();
string fullFileName = Path.Combine(currentFolderPath, selectedString);
DisplayFileInfo(fullFileName);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
. Folders
.)( DisplayFolderList
protected void OnListBoxFoldersSelected(object sender, EventArgs e)
{
try
{
string selectedString = listBoxFolders.SelectedItem.ToString();
string fullPathName = Path.Combine(currentFolderPath, selectedString);
DisplayFolderList(fullPathName);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
.)( DisplayFolderList up
FileInfo.DirectoryName .
.
protected void OnUpButtonClick(object sender, EventArgs e)
{
try
{
string folderPath = new FileInfo(currentFolderPath).DirectoryName;
DisplayFolderList(folderPath);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
-2-21
)( Delete MoveTo()
)( Move Directory File . DirectoryInfo FileInfo
. .)( Delete
FileProperties . File )( Delete )( Copy Move()
. . FilePropertiesAndMovment
.
FilePeopertiesAndMovement-1-2-21
. 34-4
370
34-4
FileProperyies .
.
.
FilePropertiesAndMovment .
) . 34-5 (.
34-5
Yes .
) ( .
.
-2-2-21 FilePropertiesAndMovment
FileProperties
. textBoxNewPath buttonMoveTo buttonCopyTo buttonDelete
.
Delete :
)protected void OnDeleteButtonClick(object sender, EventArgs e
{
try
371
09177112161 - -
C#
{
string filePath = Path.Combine(currentFolderPath,
textBoxFileName.Text);
string query = "Really delete the file\n" + filePath + "?";
if (MessageBox.Show(query,
"Delete File?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
File.Delete(filePath);
DisplayFolderList(currentFolderPath);
}
}
catch(Exception ex)
{
MessageBox.Show("Unable to delete file. The following exception"
+ " occurred:\n" + ex.Message, "Failed");
}
}
. try
.
. textBoxFileName CunentParentPath
.
protected void OnMoveButtonClick(object sender, EventArgs e)
{
try
{
string filePath = Path.Combine(currentFolderPath,
textBoxFileName.Text);
string query = "Really move the file\n" + filePath + "\nto "
+ textBoxNewPath.Text + "?";
if (MessageBox.Show(query,
"Move File?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
File.Move(filePath, textBoxNewPath.Text);
DisplayFolderList(currentFolderPath);
}
}
catch(Exception ex)
{
MessageBox.Show("Unable to move file. The following exception"
+ " occurred:\n" + ex.Message, "Failed");
}
}
protected void OnCopyButtonClick(object sender, EventArgs e)
{
try
{
string filePath = Path.Combine(currentFolderPath,
textBoxFileName.Text);
string query = "Really copy the file\n" + filePath + "\nto "
+ textBoxNewPath.Text + "?";
if (MessageBox.Show(query,
"Copy File?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
File.Copy(filePath, textBoxNewPath.Text);
DisplayFolderList(currentFolderPath);
}
}
catch(Exception ex)
{
MessageBox.Show("Unable to copy file. The following exception"
+ " occurred:\n" + ex.Message, "Failed");
}
372
.)( DisplayFileInfo .
protected void DisplayFileInfo(string fileFullName)
{
FileInfo theFile = new FileInfo(fileFullName);
if (!theFile.Exists)
throw new FileNotFoundException("File not found: " + fileFullName);
textBoxFileName.Text = theFile.Name;
textBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();
textBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();
textBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();
textBoxFileSize.Text = theFile.Length.ToString() + " bytes";
// enable move, copy, delete buttons
textBoxNewPath.Text = theFile.FullName;
textBoxNewPath.Enabled = true;
buttonCopyTo.Enabled = true;
buttonDelete.Enabled = true;
buttonMoveTo.Enabled = true;
}
. DisplayFolderList
protected void DisplayFolderList(string folderFullName)
{
DirectoryInfo theFolder = new DirectoryInfo(folderFullName);
if (!theFolder.Exists)
throw new DirectoryNotFoundException("Folder not found: " + folderFullName);
ClearAllFields();
DisableMoveFeatures();
textBoxFolder.Text = theFolder.FullName;
currentFolderPath = theFolder.FullName;
// list all subfolders in folder
foreach(DirectoryInfo nextFolder in theFolder.GetDirectories())
listBoxFolders.Items.Add(NextFolder.Name);
// list all files in folder
foreach(FileInfo nextFile in theFolder.GetFiles())
listBoxFiles.Items.Add(NextFile.Name);
}
. DisableMoveFeatures
void DisableMoveFeatures()
{
textBoxNewPath.Text = "";
textBoxNewPath.Enabled = false;
buttonCopyTo.Enabled = false;
buttonDelete.Enabled = false;
buttonMoveTo.Enabled = false;
}
.)( ClearAllFields
protected void ClearAllFields()
{
listBoxFolders.Items.Clear();
listBoxFiles.Items.Clear();
textBoxFolder.Text = "";
textBoxFileName.Text = "";
textBoxCreationTime.Text = "";
textBoxLastAccessTime.Text = "";
textBoxLastWriteTime.Text = "";
textBoxFileSize.Text = "";
textBoxNewPath.Text = "";
}
373
C#
- 09177112161 -
-3-21
. FileInfo DirectoryInfo
. 2,0Net . File .
Stream .
-1-3-21
Windows Form
. 34-6
34-6
.
. :
;using System
;using System.Collections.Generic
;using System.ComponentModel
;using System.Data
;using System.Drawing
;using System.Text
;using System.Windows.Forms
;using System.IO
namespace ReadingFiles
{
partial class Form : Form
{
)(public Form
{
;)(InitializeComponent
}
)private void button_Click(object sender, EventArgs e
374
{
;)textBox.Text = File.ReadAll(textBox.Text
}
}
}
System.IO buttonl_Click
()File.ReadAll .
. . 34-7 .
34-7
File.ReadAll .
;)File.ReadAll(FilePath
;)File.ReadAll(FilePath, Encoding
.
:
;)File.ReadAll(textBox.Text, Encoding.ASCII
. ReadAllBytes
. .
ReadAllLines .
-2-3-21
2,0Net . .
FCL ReadAllLines ReadAll ReadAllBytes
WriteAllBytes WriteAll WriteAllLines .
375
C#
- 09177112161 -
Windows Forms .
. _Click1button .
)private void button_Click(object sender, EventArgs e
{
;)File.WriteAll(textBox.Text, textBox.Text
}
. c:\Testing.txt
. . . \:C
Testing.txt .
WriteAll
.
.
. WriteAllBytes WriteAll WriteAllLines
. .
WriteAll .
)File.WriteAll(FilePath, Content
.
)File.WriteAll(FilePath, Content, Encoding
WriteAllBytes WriteAllLines
. .
)private void button_Click(object sender, EventArgs e
{
string[] movies ={"Grease","Close Encounters of the Third Kind","The Day After
;}"Tomorrow
;)File.WriteAllLines("C:\Testing.txt", movies
}
. Testing.txt .
Grease
Close Encounters of the Third Kind
The Day After Tomorrow
WriteAllLines .
-3-3-21
1 . Stream .
.
.
. :
Stream
376
) ( pipe
Net. System.IO.MemoryStream .
System.Net.Sockets. NetworkStream .
Stream .
.
.
. c
.
FileInfo DirectoryInfo
.
StringWriter,
StringReader
StreamWriter,StreamReader .
34-8 System.IO .
34-8
:
:FileStream .
.
:StreamWriter,StreamReader .
BinaryWriter,BinaryReader .
.
BinaryWriter,BinryReader
#c . 34-9 .
34-9
377
C#
- 09177112161 -
.
: Long .
Write BinaryWriter
)( 8 BinaryReader.Read Long.
-4-3-21
.
.
.
.
.
-5-3-21
FileStream .
FileStream
FileStream .
FileStream .
: File .
: Mode .
: Access .
.
: Share
.
. Net.
FileMode , FileShare,FileAccess .
. .
FileMode
Append-Create-CreateNew-Open-OpenorCreateTruncate
FileAccess
Read-ReadWrite-Write
378
FileShare
Inheritable-None-Read-ReadWrite-Write
. Open Append
Truncate CreateNew .
FileShare,FileAccess (|) or .
FileStream . :
// creates file with read-write access and allows other streams read access
FileStream fs = new FileStream(@"C:\C# Projects\Project.doc",
;)FileMode.Create
// as above, but we only get write access to the file
FileStream fs = new FileStream(@"C:\C# Projects\Project.doc",
;)FileMode.Create, FileAccess.Write
// as above but other streams don't get
// fs is open
FileStream fs = new FileStream(@"C:\C# Projects\Project.doc",
;)FileMode.Create, FileAccess.Write, FileShare.None
overload
),FileAccess.ReadWrite
.(FileShare.Read FileInfo
.
;)"FileInfo myFile = new FileInfo(@"C:\C# Projects\Project.doc
;)(FileStream fs = myFile.OpenRead
;)"FileInfo myFile= new FileInfo(@"C:\C# Projects\Projectdoc
;)(FileStream fs = myFile.OpenWrite
;)"FileInfo myFile= new FileInfo(@"C:\C# Projects\Projectdoc
FileStream fs = myFile.Open(FileMode.Append, FileAccess.Write,
;)FileShare.None
;)"FileInfo myFile = new FileInfo(@"C:\C# Projects\Project.doc
;)(FileStream fs = myFile.Create
()FileInfo.OpenRead .
FileInfo.OpenWrite . ()FileInfo.Open
. .
;)(fs.Close
. .
FileStream .
ReadByte . 0
255 . -1 .
;)(int NextByte = fs.ReadByte
Read .
. ()Read .
. ByteArray .
;)int nBytesRead = fs.Read(ByteArray, , nBytes
.
379
C#
- 09177112161 -
Write . ByteArray
nByte :
;)fs.Write(ByteArray, , nBytes
-6-3-21
StreamReader
StreamReader . StreamReader
FileStream FileStream .
.
StreamReader . StreamReader
FileInfo ()CreateText ()OpenText
StreamReader . StreamReader :
;)"StreamReader sr = new StreamReader(@"C:\My Documents\ReadMe.txt
;)StreamReader sr = new StreamReader(@"C:\My Documents\ReadMe.txt",Encoding.UTF
fs FileStream
FileStream fs = new FileStream(@"C:\My Documents\ReadMe.txt",
;)FileMode.Open, FileAccess.Read, FileShare.None
;)StreamReader sr = new StreamReader(fs
myfile FileInfo
;)"FileInfo myFile = new FileInfo(@"C:\My Documents\ReadMe.txt
;)(StreamReader sr = myFile.OpenText
FileStream StreamReader .
StreamReader
:()ReadLine .
;)(string nextLine = sr.ReadLine
:()ReadToEnd .
;)(string restOfStream = sr.ReadToEnd
:()Read .
;)(int nextChar = sr.Read
// to read characters in.
;int nChars =
;]char [] charArray = new char[nChars
;)int nCharsRead = sr.Read(charArray, , nChars
380
nChars nCharRread .
StreamWriter
StreamReader . .
StreamWriter .
;)"StreamWriter sw = new StreamWriter(@"C:\My Documents\ReadMe.txt
8UTF .
. : .
StreamWriter sw = new StreamWriter(@"C:\My Documents\ReadMe.txt", true,
;)Encoding.ASCII
fs FileStream:
FileStream fs = new FileStream(@"C:\My Documents\ReadMe.txt",FileMode.CreateNew,
;(FileAccess.Write, FileShare.Read
;(StreamWriter sw = new StreamWriter(fs
myFile FileInfo:
;)"FileInfo myFile = new FileInfo(@"C:\My Documents\NewFile.txt
;)(StreamWriter sw = myFile.CreateText
StreamWriter .
StreamWriter
:()Write .
;"string nextLine = "Groovy Line
;)sw.Write(nextLine
;'char nextChar = 'a
;)sw.Write(nextChar
;]char [] charArray = new char[
// initialize these characters
;)sw.Write(charArray
.
;
;=
;]new char[
characters
;)startAtLocation, nCharsToWrite
= int nCharsToWrite
int startAtLocation
= char [] charArray
// initialize these
sw.Write(charArray,
-7-3-21 CryptoStream
-4-21
2,0Net . .
DriveInfo . DriveInfo
.
: Windows Form ListBox ) .(10-21
381
09177112161 - -
C#
10-21
. ) (
.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace DriveInfo
{
partial class Form : Form
{
public Form()
{
InitializeComponent();
}
private void Form_Load(object sender, EventArgs e)
{
DriveInfo[] di = DriveInfo.GetDrives();
foreach (DriveInfo itemDrive in di)
{
listBox.Items.Add(itemDrive.Name);
}
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
DriveInfo di = new DriveInfo(listBox.SelectedItem.ToString());
MessageBox.Show("Available Free Space: " + di.AvailableFreeSpace + "\n"
+
"Drive Format: " + di.DriveFormat + "\n" +
"Drive Type: " + di.DriveType + "\n" +
"Is Ready: " + di.IsReady.ToString() + "\n" +
"Name: " + di.Name + "\n" +
"Root Directory: " + di.RootDirectory + "\n" +
"ToString() Value: " + di.ToString() + "\n" +
"Total Free Space: " + di.TotalFreeSpace + "\n" +
"Total Size: " + di.TotalSize + "\n" +
"Volume Label: " + di.VolumeLabel.ToString(), di.Name +
" DRIVE INFO");
}
}
}
DriveInfo foreach ListBox
. 11-21 .
11-21
.
.
-5-21
1,1/1,0Net . . ACL .
COM . 2,0Net . ACL
System.Security.AccessControl .
Active Directory
.
-1-5-21 ACL
. ACL
.
;using System
;using System.Collections.Generic
;using System.Text
;using System.IO
;using System.Security.AccessControl
namespace ConsoleApplication
{
class Program
{
;static string myFilePath
)static void Main(string[] args
{
;)" Console.Write("Provide full file path:
;)(myFilePath = Console.ReadLine
try
{
using (FileStream myFile = new FileStream(myFilePath,
))FileMode.Open, FileAccess.Read
{
;)(FileSecurity fileSec = myFile.GetAccessControl
foreach (FileSystemAccessRule fileRule in
fileSec.GetAccessRules(true, true,
)))typeof(System.Security.Principal.NTAccount
{
383
09177112161 - -
C#
. System.Security.AccessControl
FileStream . FileSystemAccessRule FileSecurity
ACL -2-5-21
. ACL
. ACL . ACL
try
{
using (FileStream myFile = new FileStream(myFilePath,
FileMode.Open, FileAccess.ReadWrite))
{
FileSecurity fileSec = myFile.GetAccessControl();
Console.WriteLine("ACL list before modification:");
foreach (FileSystemAccessRule fileRule in
fileSec.GetAccessRules(true, true,
typeof(System.Security.Principal.NTAccount)))
{
Console.WriteLine("{} {} {} access for {}", myFilePath,
fileRule.AccessControlType == AccessControlType.Allow ?
"provides" : "denies",
fileRule.FileSystemRights,
fileRule.IdentityReference.ToString());
}
Console.WriteLine();
Console.WriteLine("ACL list after modification:");
FileSystemAccessRule newRule = new FileSystemAccessRule(
new System.Security.Principal.NTAccount(@"PUSHKIN\Tuija"),
FileSystemRights.FullControl,
AccessControlType.Allow);
fileSec.AddAccessRule(newRule);
File.SetAccessControl(myFilePath, fileSec);
foreach (FileSystemAccessRule fileRule in
fileSec.GetAccessRules(true, true,
typeof(System.Security.Principal.NTAccount)))
{
384
Console.WriteLine("{} {} {} access for {}", myFilePath,
? fileRule.AccessControlType == AccessControlType.Allow
"provides" : "denies",
fileRule.FileSystemRights,
;))(fileRule.IdentityReference.ToString
}
}
}
ACL .
FileSystemAccessRule . NTAccount
FullControl . AddAccessRule FileSecurity
. SetAccessControl File FileSecurity
.
.
ACL .
;)fileSec.AddAccessRule(newRule
:
;)fileSec.RemoveAccessRule(newRule
-6-21
System.IO.
Directory File
Path .
()File.ReadAll .
WriteAll
.
Stream . .
FileStream .
StreamReader
DriveInfo
.
385
C#
- 09177112161 -
2,0Net . ACL
System.Security.AccessControl .
386
SELECT SQL .
2005VS .
-1-22
. 2005VS
.
SQL server
C#
- 09177112161 -
"
.
. Microsoft Access
.
Access
"
. ) Access ( .
.
. firstName
.
.
.
) ( FirstName LastName .
.
FirstName EmployeeID 1-22 ....
.
1-22
388
" SQL
.
.
. SQL
.
SQL .
#VC
SQL .
.
.
) ( .
.
SQL . SQL
.
. 1 .
SELECT SQL
SQL .
) ( ANSI .
ANSI SQL .
"
.
Stored procedure
389
C#
- 09177112161 -
Employees . * SELECT .
Employees .
Employees
* :
;SELECT [First Name], [Last Name] FROM Employees
" ] [ .
BY .
390
. :
Angela Dunn
David Dunstan
Zebedee Dean
"
" ."
. A
Z .
.
.
. ORDER BY DESC
. .
SELECT [First Name], [Last Name] FROM Employees
;WHERE [Last Name] LIKE D* ORDER BY [First Name] DESC
:
Zebedee Dean
David Dunstan
Angela Dunn
: "
ORDER BY ASC .
.
SELECT :
SELECT select-list
FROM table-name
][WHERE search-condition
]][ORDER BY order-by-expression [ASC | DESC
select-list" *
. table-list .
WHERE SELECT . search-condition
. ORDER BY .
order-by-expression .
ASC DESC .
SQL
.
SQL .
.
391
C#
- 09177112161 -
Products
Description
DVD
-2-22
2005#C :
TableAdapter Bindingsource .DataSet BindingSource DataSet 2-22
Data . TableAdapter
.
2-22
: "
.NET .
.
.
DataSet
Dataset .
.
DataView
. .
DataSet .
) ( .
.
392
XML . DataSet XML
XML . XML
.
DataSet
.
.
.
.
DataGridView
.
.
.
.
BindingSource
) (DataSet
.
.
DataSet DataGridview
.
DataGridView Bindingsource DataSet
. .
BindingNavigator
BindingNavigator
. Access .
DataGridView BindingSource
. Next
BindingNavigator BindingSource
BindingSource ) DataSet (
.
TableAdapter
: .DataAdapter
.
.
393
C#
- 09177112161 -
.
DataSet .
SELECT UPDATE
INSERT DELETE .
.
-3-22
BindingSource
.
.
#VC"
DataGridView .TextBox BindingSource
DataGridview .
TextBox .
-1-22 DataGridView
394
(3 Choose DataSource
Add Project DataSource . DataSource Configuration Wizard
.
(4 Choose a DataSource Type
. 4-22
.
SQL Server Oracle Access ....
Database .
Web Service . objects
.
Database Next .
4-22
Microsoft
2003office
C:\Program
.
395
C#
- 09177112161 -
.
YES .
(8
File . Next .
(9 Choose Your Data Objects
.
.
Views
4-22 .
.
finish ) .
CustomerQuery(.
DataSet NorthWindDataSet BindingSource
CustomerQueryBindingSource TableAdapter CustomerQueryTableAdapter
.
5-22
Enable Column
Reoerdering . .
396
-11 DataGridView Properties Dock Fill
.
-12 . DataGrid
.
. .
.
.
.
-2-22 TextBox
-3 TextBox . Properties
) (DataBindings . Text
. DataSource 6-22
. Add Project DataSource .
Configuration Wizard 1-22 .
6-22
397
DataSource
C#
- 09177112161 -
Add
Connection .
-6 Add Connection Browse NorthWind
Next .
.
. Yes .
-7 Save the Connection String to the Application Configuration File
Next .
-8 Choose Your DataBase Objects Tables
Database Objects . Tables Customers
. CompanyName
ContactName ContactTitle Finish .
-9 Properties Text .
DataSource 7-22 .
Other
398
399
C#
- 09177112161 -
SQL .
SELECT.
DataGridView TextBox .
.
2005VS
.
.
.
.
400
SQL SERVER ADO.NET
:
ADO.NET
DateView ADO.NET
ADO.NET
.
SQL Server
-1-23
.
.
.
DataAdapter DataSet
.
.
.
C#
- 09177112161 -
ADO.NET . ADO.NET
.
DataSet
.
. .
) TextBox(
CurrencyManager .
SQL Server
SqlClient
. SqlClient ) OleDb
Access ( SQL
Server .
2000SQL Server 7SQL Server SQL
2005Server .
) (Pubs .
ADO.NET-2-23
NET
ADO.NET ADO.NET . .
.
.
.
DataSet . DataTable
. SELECT
.
.
.
.
402
-1-2-23 Data
ADO.NET System.Data
System.Data.OleDb .System.Data.SqlClient
System.Data.SqlClient SQL
Server . System.Data.OleDb
) OLE (Access .
System.Data System.Data.OracleClient
.System.Data.Odbc OracleClient
Oracle .
SqlClient
Oracle . Odbc
ODBC OleDB .
OracleClient OleDb SqlCient Odbc ADO.NET
. .NET
.
SqlClient SQL Server .
ADO.NET .
OleDB OleDB
. ADO.NET
.
.
.
.
:
SqlConnection
SqlCommand
SqlDataAdapter
SqlParameter
SQL Server .
OLEDB
System.Data.SqlClient using
. :
;using System.Data.SqlClient
ADO.NET DataSet DataView System.Data
. .
403
C#
SqlClient
.
-2-2-23 :SqlConnection
SqlConnection
.
ConnectionString .
.
ConnectionString
. VS
Add Connction SqlConnection .
ConnectionString .
.
ring ConnectionSt
ConnectionString
. SQL Server
) SqlClient (
Server Database .
Server
.
SQL Server .
SQL Server
local localhost .
SQL Server
.
SQL Server
\ SQL Server
.
Database
) .(Pubs
SQL Server
SQL Server .
ConnectionString . SQL Server .
404
:
ConnectionString .
: .
SQL Server
ConnectionString .
User ID
.
SQL Server
.
Password
SQL Server
.
ConnectionString
Integrated
localhost SQL
. Database .
ConnectionString Pubs .
User ID Password
. = ;
.
ConntionString
Open Close SqlConnection .
:
405
C#
SqlConnection
.
-3-2-23 SqlCommand
SqlCommand SQL .
SELECT INSERT
DELETE
. SQL .
SqlCommand Overload
SqlCommand .
. SqlCommand :
;)(SqlCommand objCommand = new SqlCommand
SqlCommand
DataSet DataAdapter . INSERTSELECT ...
. SqlCommand
DataReader . DataReader Dataset
) (... .
DataSet .
Connection
SqlCommand .
Connection .
SqlConnection :
;objCommand.Connection = objConnection
SQL
Open SqlConnection .
CommandText
CommandText .
SQL .
SQL :
SqlConnection objConnection = new
SqlConnection("Server=localhost;Database=Pubs;User " +
;)";"ID=sa;Password=csdotnet
;)(SqlCommand objCommand = new SqlCommand
;objCommand.Connection = objConnection
objCommand.CommandText = "INSERT INTO authors " +
"(au_id, au_lname, au_fname, contract) " +
;")"VALUES('123-45-6789', 'Barnes', 'David', 1
406
INSERT SQL .
" authors . au_id
SQL 1
SQL
. @ SQL
.
VALUES INSERT
:
. @ .
.
.
SqlConnection objConnection = new
SqlConnection("Server=localhost;Database=Pubs;User " +
;)";"ID=sa;Password=csdotnet
;)(SqlCommand objCommand = new SqlCommand
;objCommand.Connection = objConnection
objCommand.CommandText = "INSERT INTO authors " +
"(au_id, au_lname, au_fname, contract) " +
;")"VALUES(@au_id, @au_lname, @au_fname, @au_contract
SQL
. .
Paramaters SqlCommand
.
PlaceHolder
407
C#
- 09177112161 -
SQL
#C .
SqlCommand Parameters
. .
.
.
SqlConnection objConnection = new
SqlConnection("Server=localhost;Database=Pubs;User
;)";ID=sa;Password=csdotnet
;)(SqlCommand objCommand = new SqlCommand
;objCommand.Connection = objConnection
objCommand.CommandText = "INSERT INTO authors " +
"(au_id, au_lname, au_fname, contract) " +
;")"VALUES(@au_id, @au_lname, @au_fname, @au_contract
objCommand.Parameters.AddWithValue("@au_id",
;)txtAuId.Text
objCommand.Parameters.AddWithValue("@au_lname",
;)txtLastName.Text
objCommand.Parameters.AddWithValue("@au_fname",
;)txtFirstName.Text
objCommand.Parameters.AddWithValue("@au_contract",
;)chkContract.Checked
AddWithValue
Parameters .
@ au_id Text txtAuId .
@ au_lName Text txtLastName ...
ExecuteNonQuery
.
. ExecuteNonQuery
SqlCommand .
. SqlCommand
SELECT
. )
( .
SQL . .
ExecuteNonQuery .
SqlConnection objConnection = new
SqlConnection("Server=localhost;Database=Pubs;User
;)";ID=sa;Password=csdotnet
;)(SqlCommand objCommand = new SqlCommand
;objCommand.Connection = objConnection
objCommand.CommandText = "INSERT INTO authors " +
"(au_id, au_lname, au_fname, contract) " +
;")"VALUES(@au_id, @au_lname, @au_fname, @au_contract
objCommand.Parameters.AddWithValue("@au_id",
;)txtAuId.Text
objCommand.Parameters.AddWithValue("@au_lname",
408
;)txtLastName.Text
objCommand.Parameters.AddWithValue("@au_fname",
;)txtFirstName.Text
objCommand.Parameters.AddWithValue("@au_contract",
;)chkContract.Checked
;)(objConnection.Open
;)(objCommand.ExecuteNonQuery
;)(objConnection.Close
-4-2-23 SqlDataAdapter
DataAdapter
DataSet .
SqlCommand
SqlCommand SqlConnection .
DatAdapter SqlCommand SqlConnection
.
DataAdapter SelectCommand
. DataAdapter
DataSet DataTable
. Datadapter
InsertCommand DeleteCommand UpdateCommand SqlCommand
DataAdapter
.
DataAdapter
.
.
SELECT .
DataAdapter SELECT . VS
CommandBuilder SELECT UPDATEINSERT
DELETE . SelectCommand
. CommandBuilder .
SelectCommand
409
C#
- 09177112161 -
DataAdapter
SelectCommand DataAdapter . SqlCommand
.
SqlCommand
. :
:Connection SqlConnection
.
:CommandText SQL
.
SQL
DataAdapter :
// Declare a SqlDataAdapter object...
;)(SqlDataAdapter objDataAdapter = new SqlDataAdapter
// Assign a new SqlCommand to the SelectCommand property
;)(objDataAdapter.SelectCommand = new SqlCommand
// Set the SelectCommand properties...
;objDataAdapter.SelectCommand.Connection = objConnection
= objDataAdapter.SelectCommand.CommandText
"SELECT au_lname, au_fname FROM authors " +
;""ORDER BY au_lname, au_fname
410
SqlDataAdapter .
SelectCommand . SqlCommand
Connection
. CommandText SQL
.
SelectCommand
. SQL
.
usp_select SQL
. :
// Declare a SqlDataAdapter object...
;)(SqlDataAdapter objDataAdapter = new SqlDataAdapter
// Assign a new SqlCommand to the SelectCommand property
;)(objDataAdapter.SelectCommand = new SqlCommand
// Set the SelectCommand properties...
;objDataAdapter.SelectCommand.Connection = objConnection
;"objDataAdapter.SelectCommand.CommandText = "usp_select
= objDataAdapter.SelectCommand.CommandType
;CommandType.StoredProcedure
SQL CommandText
.
CommandText .SQL
CommandType . CommandType.Text
SQL .
CommandType.StoredProcedure CommandText
.
CommandBuilder SQL
SelectCommand DataAdapter
DataSet .
. SQL
DataAdapter
.
SQL .
CommandBuilder SELECT
DataAdapter UPDATE INSERT DELETE .
.
// Declare a SqlDataAdapter object...
;)(SqlDataAdapter objDataAdapter = new SqlDataAdapter
// Assign a new SqlCommand to the SelectCommand property
;)(objDataAdapter.SelectCommand = new SqlCommand
411
09177112161 - -
C#
.
. DataSet
Fill
DataSet .
.
.
.
Fill
: ObjDataSet authors
// Declare a SqlDataAdapter object...
SqlDataAdapter objDataAdapter = new SqlDataAdapter();
// Create an instance of a new select command object
objDataAdapter.SelectCommand = new SqlCommand();
// Set the SelectCommand properties...
objDataAdapter.SelectCommand.Connection = objConnection;
objDataAdapter.SelectCommand.CommandText = "usp_select";
objDataAdapter.SelectCommand.CommandType =
CommandType.StoredProcedure;
DataSet objDataSet = new DataSet();
// Fill the DataSet object with data...
objDataAdapter.Fill(objDataSet, "authors");
412
-5-2-23 DataSet
DataSet .
.
. DataView
.
.
DataAdapter .
DataSet XML .
DataSet .
DataSet XML .
DataSet DataSet
.
XML DataSet ) XML
( . DataSet XSD
DataSet ) . ( 2-23
413
C#
- 09177112161 -
2-23
XML CustomerDataSet VS .
DataSet
. DataSet .
DataSet
.
.
-6-2-23 DataView
DataView
DataSet . DataView
DataSet DataView .
.
DataSet
DataTable . DataAdapter DataSet
) ( DataTable
DataSet . DataView
DataSet .
SQL .
DataView DataSet
. authors DataSet LastName
DataView
FirstName LastName DataView LastName
authors FirstName . . .
DataView DataTable
DataTable .
DataView
. DataView authors ObjDataSet .
414
Tables DataSet
.
// Set the DataView object to the DataSet object...
DataView objDataView = new
;))"DataView(objDataSet.Tables("authors
Sort
DataView DataSet
. .
Sort DataView
. authors DataView
FirstName LastName :
;"objDataView.Sort = "au_fname, au_lname
ORDER BY
DataView
. WHERE SELECT
SQL .
RowFilter .
WHERE SELECT .
" '
. authors LastName Green :
// Set the DataView object to the DataSet object...
DataView objDataView = new
;))"DataView(objDataSet.Tables("authors
;"'objDataView.RowFilter = "au_lname = 'Green
authors LastName Green :
// Set the DataView object to the DataSet object...
DataView objDataView = new
;))"DataView(objDataSet.Tables("authors
;"'objDataView.RowFilter = "au_lname <> 'Green
AND OR
. authors
FirstName D LastName Green:
= objDataView.RowFilter
;"'*"au_lname <> 'Green' AND au_fname LIKE 'D
415
C#
- 09177112161 -
Find
Find DataView .
. Find
.
ObjDataView authors
FirstName Ann . au_fname
Find Ann . :
;int intPosition
;"objDataView.Sort = "au_fname
;)"intPosition = objDataView.Find("Ann
DataView FirstName Ann
. . Find
.
Ann ANN . . .
.
.
Del Castillo Del Find
. :
;"objDataView.Sort = "au_lname
;)"intPosition = objDataView.Find("del castillo
DataView .
. .
Object
. Find .
Simon Watts . :
;int intPosition
;]Object[] arrValues = new Object[1
;"objDataView.Sort = "au_fname, au_lname
// Find the author named Simon Watts.
;"arrValues[0]= "Simon
;"arrValues[1] = "Watts
;)intPosition = objDataView.Find(arrValues
: object Find .
NET. object .
object .
. authors
25 Ann .
.
416
-3-23 ADO.NET
ADO.NET
SQL SERVER .
...
.
DataSet .
SqlCommand SqlConnection SqlDataAdapter DataSet
DataGrid
. .
.
:
.
. .
.
-1-3-23 DataSet
. pubs 2000SQL Server
. 7 2005 msde 2000SQL Server
pubs .
.
. 3-23
.
authors
titles .
titleauthor .
3-23
417
C#
- 09177112161 -
SELECT
:
SELECT au_lname, au_fname, title, price
FROM authors
JOIN titleauthor ON authors.au_id = titleauthor.au_id
JOIN titles ON titleauthor.title_id = titles.title_id
ORDER BY au_lname, au_fname
. authors titles
authors .
au_id authors titleauthor .
authors titleauthor
au_id authors .
titles titleauthor title_id
. titleauthor
titles .
.
: SELECT
.
SELECT
. .
1-23
(1 VS DATASETEXAMPLE .
(2 Properties :
Size 600/ 230 .
418
StartPosition CenterScreen .
Text Bound DataSet .
(3 Data DataGridView
:
Name grdAuthorTitles .
Anchor Top/Left/Right/Bottom .
Location 0/ 0 .
Size 592/ 203 .
(4 1Form
. 1Form :
// Using Data and SqlClient namespaces...
;using System.Data
;using System.Data.SqlClient
public partial class Form1 : Form
{
}
(5 .
.
ConnectionString .
public partial class Form1 : Form
{
(SqlConnection objConnection = new SqlConnection
"server=localhost;database=pubs;" +
;)"="user id=sa;password
;)(SqlDataAdapter objDataAdapter = new SqlDataAdapter
;)(DataSet objDataSet = new DataSet
)(public Form1
{
:
Server SQL Server .
Password,User ID
. .
Password ConnectionString
. .;=Password
(6 Forml load
. :
)private void Form1_Load(object sender, EventArgs e
{
// Set the SelectCommand properties...
;)(objDataAdapter.SelectCommand = new SqlCommand
= objDataAdapter.SelectCommand.Connection
;objConnection
= objDataAdapter.SelectCommand.CommandText
"SELECT au_lname, au_fname, title, price " +
"FROM authors " +
"JOIN titleauthor ON authors.au_id = " +
"titleauthor.au_id " +
"JOIN titles ON titleauthor.title_id = " +
419
C#
(7 4-23 .
4-23
(8 DataGridView .
.
.
:
.
2-23
-1 DataGridView :
-
- ) (.
-2 form_Load :
)private void Form1_Load(object sender, EventArgs e
{// Set the SelectCommand properties...
;)(objDataAdapter.SelectCommand = new SqlCommand
= objDataAdapter.SelectCommand.Connection
;objConnection
= objDataAdapter.SelectCommand.CommandText
420
.
. 5-23 . -3
4-23
5-23
421
C#
- 09177112161 -
-4-23
DataGridView .
.
.
TextBox
.
.
.
.
RadioButton CheckBox TextBox .
ListBox ComboBox DataGridView
.
:CurrencyManager,BindingContext-1-4-23
BindingContext .
.
BindingContext CurrencyManager .
CurrencyManager ) ( DataSet
.
.
CurrencyManager DataTable DataSet
DataSetView DataView .
CurrencyManager .
.
CurrencyManager
CurrencyManager BindingContext .
422
CurrencyManager BindingContext
.
DataSet
CurrencyManager Authors .
CurrencyManager . CurrencyManager
objDataSet BindingContext . BindingContext
CurrencyManager ) ( CurrencyManager
:
;CurrencyManager objCurrencyManager
= objCurrencyManager
;)](CurrencyManager)(this.BindingContext[objDataSet
Position
. :
CurrencyManager
.
;objCurrencyManager.Position += 1
objDataSet
:
;objCurrencyManager.Position -= 1
objDataSet :
;objCurrencyManager.Position = 0
Count CurrencyManager
CurrencyManager .
:
;objCurrencyManager.Position = objCurrencyManager.Count - 1
.
.
.
-2-4-23
DataBindings .
DataBindingsCollection . Add
. :
object.DataBindings.Add(propertyName,
;)dataSource, dataMember
:
:Object .
:propertyName .
423
C#
- 09177112161 -
:dataSource
DataTable DataView DataSet .
:dataMember propertyName
.
.
Clear ControlBindingsCollection .
. :
;)(txtFirstName.DataBindings.Clear
(5 GroupBox :
o
Size 128;408 .
Location 8;8 .
Text
Size
Location
Name
False
Last Name
16;64
26;8
Label1
False
First Name
16;64
50;8
Label2
False
Book Title
16;56
74;8
Label3
False
Price
16;64
98;8
Label4
(7 TextBox GroupBoxl
:
ReadOnly
Size
Location
Name
True
20;88
24;72
txtLastName
True
20;88
48;72
txtFirstName
False
20;328
72;72
txtBookTitle
False
20;48
96;72
txtPrice
425
09177112161 - -
C#
GroupBox ( 8
:
. 144;8 Location
. 168;408 Size
. Navigation Text
: 2GroupBox Label ( 9
Name
Location
Size
Text
AutoSize
Label5
23;8
16;64
Field
False
Label6
48;8
16;80 SearchCriteria
False
Location
Size
TabStop
TextAlign
txtSearchCriteria
48;88
20;200
txtRecordPosition
130;152
20;85
False
Center
: 2GroupBox Button ( 12
Name
Location
Size
Text
ToolTip On
ToolTip1
btnPerformSort
16;304
24;96
Perform Sort
btnPerformSearch
48;304
24;96
Perform
Search
btnNew
88;40
24;72
New
btnAdd
88;120
24;72
Add
btnUpdate
88;200
24;72
Update
btnDelete
88;280
24;72
Delete
btnMoveFirst
128;88
24;29
>|
Move First
btnMovePrevious
128;120
24;29
>
Move
Previous
btnMoveNext
128;200
24;29
<
Move Next
btnMoveLast
128;272
24;29
|<
Move Last
426
. StatusLabel .
. 6-23 ( 14
Forml .( 15
: System.Data.SqlClient System.Data
// Import Data and SqlClient namespaces
using System.Data;
using System.Data.SqlClient;
.( 16
. SQL
: Forml
public partial class Form1 : Form
{
// Constant strings
private const string _CommandText =
"SELECT authors.au_id, au_lname, au_fname, " +
"titles.title_id, title, price " +
"FROM authors " +
"JOIN titleauthor ON authors.au_id = " +
"titleauthor.au_id " +
"JOIN titles ON titleauthor.title_id = " +
"titles.title_id " +
"ORDER BY au_lname, au_fname";
private const string _ConnectionString =
"server=localhost;database=pubs;" +
"user id=sa;password=;";
// Declare global objects...
SqlConnection objConnection;
SqlDataAdapter objDataAdapter;
DataSet objDataSet;
DataView objDataView;
CurrencyManager objCurrencyManager;
ConnectionString :
Password-User ID.
. localhost
:( 17
public Form1()
{
objConnection = new SqlConnection(_ConnectionString);
objDataAdapter = new SqlDataAdapter(_CommandText, bjConnection);
InitializeComponent();
}
. FillDataSetAndView ( 18
: Forml .
private void FillDataSetAndView()
{
// Initialize a new instance of the DataSet object...
objDataSet = new DataSet();
// Fill the DataSet object with data...
objDataAdapter.Fill(objDataSet, "authors");
// Set the DataView object to the DataSet object...
objDataView = new DataView(
objDataSet.Tables["authors"]);
// Set our CurrencyManager object
// to the DataView object...
objCurrencyManager = (CurrencyManager)( this.BindingContext[objDataView]);
}
427
09177112161 - -
C#
( 19
: DataView
private void BindFields()
{
// Clear any previous bindings...
txtLastName.DataBindings.Clear();
txtFirstName.DataBindings.Clear();
txtBookTitle.DataBindings.Clear();
txtPrice.DataBindings.Clear();
// Add new bindings to the DataView object...
txtLastName.DataBindings.Add("Text",
objDataView, "au_lname");
txtFirstName.DataBindings.Add("Text",
objDataView, "au_fname");
txtBookTitle.DataBindings.Add("Text",
objDataView, "title");
txtPrice.DataBindings.Add("Text",
objDataView, "price");
// Display a ready status...
ToolStripStatusLabel1.Text = "Ready";
}
:( 20
private void ShowPosition()
{
// Always format the number
// in the txtPrice field to include cents
try
{
txtPrice.Text =
Decimal.Parse(txtPrice.Text).ToString("##0.00");
}
catch(System.Exception e)
{
txtPrice.Text = "0";
txtPrice.Text =
Decimal.Parse(txtPrice.Text).ToString("##0.00");
}
// Display the current position
// and the number of records
txtRecordPosition.Text =
(objCurrencyManager.Position + 1) +
" of " + objCurrencyManager.Count;
}
( 21
. .
)Load
.(GroupBox
:
private void Form1_Load(object sender, EventArgs e)
{
// Add items to the combo box...
cboField.Items.Add("Last Name");
cboField.Items.Add("First Name");
cboField.Items.Add("Book Title");
cboField.Items.Add("Price");
// Make the first item selected...
cboField.SelectedIndex = 0;
// Fill the DataSet and bind the fields...
FillDataSetAndView();
BindFields();
// Show the current record position...
ShowPosition();
}
428
(22 .
btnMoveLast btnMovePrevious btnMoveNext
btnMoveFirst .
Click btnMoveFirst :
)private void btnMoveFirst_Click(object sender, EventArgs e
{
// Set the record position to the first record...
;objCurrencyManager.Position = 0
// Show the current record position...
;)(ShowPosition
}
(23 Click btnMovePrevious :
private void btnMovePrevious_Click(object sender,
)EventArgs e
{
// Move to the previous record...
;objCurrencyManager.Position -= 1
// Show the current record position...
;)(ShowPosition
}
(24 btnMoveNext_Click :
)private void btnMoveNext_Click(object sender, EventArgs e
{
// Move to the next record...
;objCurrencyManager.Position += 1
//Show the current record position...
;)(ShowPosition
}
(25 btnMoveLast_Click :
)private void btnMoveLast_Click(object sender, EventArgs e
{
// Set the record position to the last record...
= objCurrencyManager.Position
;objCurrencyManager.Count - 1
// Show the current record position...
;)(ShowPosition
}
(26 .
. DataView .
CurrencyManager
.
7-23 .
.
.
.
7-23
429
C#
- 09177112161 -
.
.
. .
: .
.
-4-23
(1 Forml Perform Sort
Click . :
private void btnPerformSort_Click(object sender,
)EventArgs e
{
// Determine the appropriate item selected and set the
// Sort property of the DataView object...
)switch(cboField.SelectedIndex
{
case 0: // Last Name
;"objDataView.Sort = "au_lname
;break
case 1: // First Name
;"objDataView.Sort = "au_fname
;break
case 2: // Book Title
;"objDataView.Sort = "title
;break
case 3: // Price
;"objDataView.Sort = "price
;break
}
// Call the click event for the MoveFirst button...
;)btnMoveFirst_Click(null, null
// Display a message
// that the records have been sorted...
;"ToolStripStatusLabel1.Text = "Records Sorted
}
430
ComboBox . ( 2
-23 . Perform Sort
Price 8
8-23
-5-23
Click Perform Search ( 1
: .
private void btnPerformSearch_Click(object sender,
EventArgs e)
{
// Declare local variables...
int intPosition;
// Determine the appropriate item selected and set the
// Sort property of the DataView object...
switch(cboField.SelectedIndex)
{
case 0: // Last Name
objDataView.Sort = "au_lname";
break;
case 1: // First Name
objDataView.Sort = "au_fname";
break;
case 2: // Book Title
objDataView.Sort = "title";
break;
case 3: // Price
objDataView.Sort = "price";
break;
}
// If the search field is not price then...
if (cboField.SelectedIndex < 3)
{
// Find the last name, first name, or title...
intPosition =objDataView.Find(txtSearchCriteria.Text);
}
else
{
// otherwise find the price...
intPosition = objDataView.Find(
431
C#
09177112161 -;))Decimal.Parse(txtSearchCriteria.Text
}
)if (intPosition == -1
{
// Display a message
// that the record was not found...
;"ToolStripStatusLabel1.Text = "Record Not Found
}
else
{
// Otherwise display a message that the record
// was found and reposition the CurrencyManager
// to that record...
;"ToolStripStatusLabel1.Text = "Record Found
;objCurrencyManager.Position = intPosition
}
// Show the current record position...
;)(ShowPosition
}
(2 .
ComboBox Search Criteria .
Perform Search .
.
) .(9-23
.
9-23
-6-23
(1 Forml btnNew click
. :
)private void btnNew_Click(object sender, EventArgs e
{
// Clear the book title and price fields...
;"" = txtBookTitle.Text
;"" = txtPrice.Text
432
. btnAdd_Click ( 2
.
.
. Click Add
:
private void btnAdd_Click(object sender, EventArgs e)
{
// Declare local variables and objects...
int intPosition, intMaxID;
String strID;
SqlCommand objCommand = new SqlCommand();
// Save the current record position...
intPosition = objCurrencyManager.Position;
// Create a new SqlCommand object...
SqlCommand maxIdCommand = new SqlCommand(
"SELECT MAX(title_id)" +
"FROM titles WHERE title_id LIKE 'DM%'",
objConnection);
// Open the connection, execute the command
objConnection.Open();
Object maxId = maxIdCommand.ExecuteScalar();
// If the MaxID column is null...
if (maxId == DBNull.Value)
{
// Set a default value of 1000...
intMaxID = 1000;
}
else
{
// otherwise set the strID variable
// to the value in MaxID...
strID = (String)maxId;
// Get the integer part of the string...
intMaxID = int.Parse(strID.Remove(0, 2));
// Increment the value...
intMaxID += 1;
}
// Finally, set the new ID...
strID = "DM" + intMaxID.ToString();
// Set the SqlCommand object properties...
objCommand.Connection = objConnection;
objCommand.CommandText = "INSERT INTO titles " +
"(title_id, title, type, price, pubdate) " +
"VALUES(@title_id,@title,@type,@price,@pubdate);" +
"INSERT INTO titleauthor (au_id, title_id) " +
"VALUES(@au_id,@title_id)";
// Add parameters for the placeholders in the SQL in
// the CommandText property...
// Parameter for the title_id column...
objCommand.Parameters.AddWithValue("@title_id",
strID);
// Parameter for the title column...
objCommand.Parameters.AddWithValue("@title",
txtBookTitle.Text);
// Parameter for the type column
objCommand.Parameters.AddWithValue("@type", "Demo");
// Parameter for the price column...
objCommand.Parameters.AddWithValue("@price",
txtPrice.Text).DbType = DbType.Currency;
// Parameter for the pubdate column
objCommand.Parameters.AddWithValue("@pubdate",
DateTime.Now);
// Parameter for the au_id column...
objCommand.Parameters.AddWithValue("@au_id",
this.BindingContext[objDataView,"au_id"].Current);
// Execute the SqlCommand object
// to insert the new data...
433
C#
09177112161 -try
{
;)(objCommand.ExecuteNonQuery
}
)catch(SqlException SqlExceptionErr
{
;)MessageBox.Show(SqlExceptionErr.Message
}
// Close the connection...
;)(objConnection.Close
// Fill the dataset and bind the fields...
;)(FillDataSetAndView
;)(BindFields
// Set the record position
// to the one that you saved...
;objCurrencyManager.Position = intPosition
// Show the current record position...
;)(ShowPosition
// Display a message that the record was added...
;"ToolStripStatusLabel1.Text = "Record Added
}
ExecuteScalar SQL .
(3
Add . Price BookTitle
10-23 . .
10-23
(4
Add .
.
.
11-23
434
-7-23
. click btnUpdate ( 1
:
private void btnUpdate_Click(object sender, EventArgs e)
{
// Declare local variables and objects...
int intPosition;
SqlCommand objCommand = new SqlCommand();
// Save the current record position...
intPosition = objCurrencyManager.Position;
// Set the SqlCommand object properties...
objCommand.Connection = objConnection;
objCommand.CommandText = "UPDATE titles " +
"SET title = @title, price = @price " +
"WHERE title_id = @title_id";
objCommand.CommandType = CommandType.Text;
// Add parameters for the placeholders in the SQL in
// the CommandText property...
// Parameter for the title field...
objCommand.Parameters.AddWithValue("@title",
txtBookTitle.Text);
// Parameter for the price field...
objCommand.Parameters.AddWithValue("@price",
txtPrice.Text).DbType = DbType.Currency;
// Parameter for the title_id field...
objCommand.Parameters.AddWithValue("@title_id",
this.BindingContext[objDataView,"title_id"].Current);
// Open the connection...
objConnection.Open();
// Execute the SqlCommand object to update the data...
objCommand.ExecuteNonQuery();
// Close the connection...
objConnection.Close();
// Fill the DataSet and bind the fields...
FillDataSetAndView();
BindFields();
// Set the record position
// to the one that you saved...
objCurrencyManager.Position = intPosition;
// Show the current record position...
ShowPosition();
// Display a message that the record was updated...
ToolStripStatusLabel1.Text = "Record Updated";
}
435
09177112161 - -
C#
.( 2
. Price .
. Update
.
12-23
-8-23
click btnDelete
: .
private void btnDelete_Click(object sender, EventArgs e)
{
// Declare local variables and objects...
int intPosition;
SqlCommand objCommand = new SqlCommand();
// Save the current record position - 1 for the one to
// be deleted...
intPosition =this.BindingContext[objDataView].Position - 1;
// If the position is less than 0 set it to 0...
if( intPosition < 0 )
intPosition = 0;
// Set the Command object properties...
objCommand.Connection = objConnection;
objCommand.CommandText = "DELETE FROM titleauthor " +
"WHERE title_id = @title_id;" +
"DELETE FROM titles WHERE title_id = @title_id";
// Parameter for the title_id field...
objCommand.Parameters.AddWithValue("@title_id",
this.BindingContext[objDataView,"title_id"].Current);
// Open the database connection...
objConnection.Open();
// Execute the SqlCommand object to update the data...
objCommand.ExecuteNonQuery();
// Close the connection...
objConnection.Close();
// Fill the DataSet and bind the fields...
FillDataSetAndView();
BindFields();
// Set the record position
// to the one that you saved...
436
(1
= this.BindingContext[objDataView].Position
;intPosition
// Show the current record position...
;)(ShowPosition
// Display a message that the record was deleted...
;"ToolStripStatusLabel1.Text = "Record Deleted
}
(2 .
.
Delete . pubs
SQL Server
.
.
.
sales .
.
13-23
-5-23
ADO.NET SqlDataAdapter SqlCommand SqlConnection
SqlParameter
.
SQL Server .
OleDb System.Data.OleDb .
DataSet DataView System.Data
.
437
C#
- 09177112161 -
CurrencyManager .
.
438
. System.Threading
.
CLR
.
1 .
.
2
. .
.
. ) (
.
. .
.
Kill
MultiThread
C#
- 09177112161 -
. .
.
)
( .
.
.
-1-24
.
Pi 10 .
. .
.
.
.
:
.
.
. .
Pi .
.
. .
-1-1-24
Thread . Thread
CLR . ThreadStart
. "
" . ThreadStart .
;)(public delegate void ThreadStart
void
. .
;) )Thread myThread = new Thread( new ThreadStart(myFunc
: 1000 .
)(public void Incrementer
{
)for (int i =0;i<1000;i++
{
;)Console.WriteLine("Incrementer: {0}", i
}
440
}
public void Decrementer()
{
for (int i = 1000;i>=0;i--)
{
Console.WriteLine("Decrementer: {0}", i);
}
}
ThreadStart
. .
Thread t1 = new Thread( new ThreadStart(Incrementer) );
Thread t2 = new Thread( new ThreadStart(Decrementer) );
Thread Start .
.
t1.Start();
t2.Start();
. :
System.Threading Using . 1-24
1t 2t . Thread
.
1-24
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
#endregion
namespace UsingThreads
{
class Tester
{
static void Main( )
{
// make an instance of this class
Tester t = new Tester( );
Console.WriteLine( "Hello" );
// run outside static Main
t.DoTest( );
}
public void DoTest( )
{
// create a thread for the Incrementer
// pass in a ThreadStart delegate
// with the address of Incrementer
Thread t1 =
new Thread(
new ThreadStart( Incrementer ) );
// create a thread for the Decrementer
// pass in a ThreadStart delegate
// with the address of Decrementer
Thread t2 =
new Thread(
new ThreadStart( Decrementer ) );
441
C#
106 . 1000
. .
:
.
-2-1-20
.
(1t) 1 (2t) 2.
;) (t2.Join
1t 1t 2t .
()Main
. MyThreads .
.
)foreach (Thread myThread in myThreads
442
{
;)(myThread.Join
}
;)"Console.WriteLine("All my threads are done.
.
.
-3-1-20 Sleep
.
.
.
Thread . overload .
int timeSpan .
) . 2000 2(
timespan )100 ( ()Sleep .
()Thread.Sleep
.
;)Thread.Sleep(1000
Sleep .
.
1-24 ( (1Thread.Sleep Writeln
.
)for (int i =0;i<1000;i++
{
;)Console.WriteLine( "Incrementer: {0}", i
;)Thread.Sleep(1
}
.
.
Incrementer: 0
Incrementer: 1
Decrementer: 1000
Incrementer: 2
Decrementer: 999
Incrementer: 3
Decrementer: 998
Incrementer: 4
Decrementer: 997
Incrementer: 5
Decrementer: 996
443
C#
09177112161 -Incrementer: 6
Decrementer: 995
-4-1-24
. .
KeepAlive .
.
()Thread.Interupt .
Thread. Abort .
ThreadAbortException .
ThreadAbortException .
.
Cancel .
Cancel 1t 2t .
Abort 1t .
;)(t1.Abort
1t 1t .
2-24 Thread .
IsBackground True (
) . (
1Thread ) .2Thread
50 .
50 ()Abort .
.
. All My Thread Are
Done . 2-24 .
2-24
#region Using directives
;using System
;using System.Collections.Generic
;using System.Text
;using System.Threading
#endregion
namespace InterruptingThreads
{
class Tester
{
) (static void Main
{
// make an instance of this class
;) (Tester t = new Tester
// run outside static Main
;) (t.DoTest
444
}
public void DoTest( )
{
// create an array of unnamed threads
Thread[] myThreads =
{
new Thread( new ThreadStart(Decrementer) ),
new Thread( new ThreadStart(Incrementer) ),
new Thread( new ThreadStart(Decrementer) ),
new Thread( new ThreadStart(Incrementer) )
};
// start each thread
int ctr = 1;
foreach (Thread myThread in myThreads)
{
myThread.IsBackground = true;
myThread.Start( );
myThread.Name = "Thread" + ctr.ToString( );
ctr++;
Console.WriteLine("Started thread {0}",
myThread.Name);
Thread.Sleep(50);
}
// ask the first thread to stop
myThreads[0].Interrupt( );
// tell the second thread to abort immediately
myThreads[1].Abort( );
// wait for all threads to end before continuing
foreach (Thread myThread in myThreads)
{
myThread.Join( );
}
// after all threads end, print a message
Console.WriteLine("All my threads are done.");
}
// demo function, counts down from 100
public void Decrementer( )
{
try
{
for (int i = 100; i >= 0; i--)
{
Console.WriteLine(
"Thread {0}. Decrementer: {1}",
Thread.CurrentThread.Name,
i);
Thread.Sleep(1);
}
}
catch (ThreadAbortException)
{
Console.WriteLine(
"Thread {0} aborted! Cleaning up...",
Thread.CurrentThread.Name);
}
catch (System.Exception e)
{
Console.
WriteLine("Thread has been interrupted ");
}
finally
445
09177112161 - {
Console.WriteLine(
"Thread {0} Exiting. ",
Thread.CurrentThread.Name);
} }
// demo function, counts up to 100
public void Incrementer( )
{
try
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(
"Thread {0}. Incrementer: {1}",
Thread.CurrentThread.Name,
i);
Thread.Sleep(1);
}
}
catch (ThreadAbortException)
{
Console.WriteLine(
"Thread {0} aborted!",
Thread.CurrentThread.Name);
}
catch (System.Exception e)
{
Console.
WriteLine("Thread has been interrupted");
}
finally
{
Console.WriteLine(
"Thread {0} Exiting. ",
Thread.CurrentThread.Name);
}}}}
Output (excerpt):
Started thread Thread1
Thread Thread1. Decrementer: 100
Thread Thread1. Decrementer: 99
Started thread Thread2
Thread Thread2. Incrementer: 0
Thread Thread1. Decrementer: 98
Started thread Thread3
Thread Thread3. Decrementer: 100
Thread Thread1. Decrementer: 97
Thread Thread2. Incrementer: 1
Started thread Thread4
Thread Thread4. Incrementer: 0
Thread Thread2 aborted!
Thread Thread3. Decrementer: 99
Thread Thread2 Exiting.
Thread has been interrupted
Thread Thread3. Decrementer: 98
Thread Thread4. Incrementer: 1
446
C#
Thread Thread1 Exiting.
Thread Thread3. Decrementer: 97
Thread Thread3. Decrementer: 1
Thread Thread4. Incrementer: 98
Thread Thread3. Decrementer: 0
Thread Thread4. Incrementer: 99
Thread Thread3 Exiting.
Thread Thread4 Exiting.
All my threads are done.
100 99 .
. 2thread
. 1thread
. Abort
.
.
.
-2-24
.
. .
.
: InterLock lock #C .Moniter
) .(Counter
Counter .
.
;int counter = 0
Incrementer Counter .
)(public void Incrementer
{
try
{
)while (counter < 1000
{
;int temp = counter
temp++; // increment
// simulate some work in this method
;)Thread.Sleep(1
// assign the Incremented value
// to the counter variable
// and display the results
;counter = temp
(Console.WriteLine
"Thread {0}. Incrementer: {1}",
447
C#
09177112161 -Thread.CurrentThread.Name,
;)counter
}}
.
.
Counter
Counter.
( (0Counter .
. ( (0Counter
. ) (1
Counter . 1 . 1
. 1234 . . . 123344 . . .
.
3-24 .
3-24
#region Using directives
;using System
;using System.Collections.Generic
;using System.Text
;using System.Threading
#endregion
namespace SharedResource
{
class Tester
{
;private int counter = 0
) (static void Main
{
// make an instance of this class
;) (Tester t = new Tester
// run outside static Main
;) (t.DoTest
}
) (public void DoTest
{
;) ) Thread t1 = new Thread( new ThreadStart( Incrementer
;t1.IsBackground = true
;"t1.Name = "ThreadOne
;) (t1.Start
Console.WriteLine( "Started thread {0}",
;) t1.Name
;) ) Thread t2 = new Thread( new ThreadStart( Incrementer
;t2.IsBackground = true
;"t2.Name = "ThreadTwo
;) (t2.Start
Console.WriteLine( "Started thread {0}",
;) t2.Name
;) (t1.Join
448
t2.Join( );
// after all threads end, print a message
Console.WriteLine( "All my threads are done." );
}
// demo function, counts up to 1K
public void Incrementer( )
{
try
{
while ( counter < 1000 )
{
int temp = counter;
temp++; // increment
// simulate some work in this method
Thread.Sleep( 1 );
// assign the decremented value
// and display the results
counter = temp;
Console.WriteLine(
"Thread {0}. Incrementer: {1}",
Thread.CurrentThread.Name,
counter );
}}
catch ( ThreadInterruptedException )
{
Console.WriteLine(
"Thread {0} interrupted! Cleaning up...",
Thread.CurrentThread.Name );
}
finally
{
Console.WriteLine(
"Thread {0} Exiting. ",
Thread.CurrentThread.Name );
}}}}
Output:
Started thread ThreadOne
Started thread ThreadTwo
Thread ThreadOne. Incrementer: 1
Thread ThreadOne. Incrementer: 2
Thread ThreadOne. Incrementer: 3
Thread ThreadTwo. Incrementer: 3
Thread ThreadTwo. Incrementer: 4
Thread ThreadOne. Incrementer: 4
Thread ThreadTwo. Incrementer: 5
Thread ThreadOne. Incrementer: 5
Thread ThreadTwo. Incrementer: 6
Thread ThreadOne. Incrementer: 6
Interlocked -1-2-20
) . CLR
. . Monitor ( NET
449
09177112161 - -
C#
Interlocked . Interlocked CLR
. Decrement Increment
. 3-24 Incrementer
public void Incrementer( )
{
try
{
while (counter < 1000)
{
int temp = Interlocked.Increment(ref counter);
// simulate some work in this method
Thread.Sleep(0);
// display the incremented value
Console.WriteLine(
"Thread {0}. Incrementer: {1}",
Thread.CurrentThread.Name,
temp);
}}}
450
Thread ThreadTwo. Incrementer: 20
-2-2-24
InterLocked
. .
lock #C .
lock . .
lock .
.
#C lock .
.
lock(expression) statement-block
: Incrementer lock .
)(public void Incrementer
{
try
{
)while (counter < 1000
{
;int temp
)lock (this
{
;temp = counter
;temp ++
;)Thread.Sleep(1
;counter = temp
}
// assign the decremented value
// and display the results
(Console.WriteLine
"Thread {0}. Incrementer: {1}",
Thread.CurrentThread.Name,
;)temp
}}
Catch Finally .
InterLocked.
-3-2-20
.
.
.
()Monitor.Enter
.
;)Monitor.Enter(this
451
C#
- 09177112161 -
. . ()Wait
()Pulse
()Wait . .
: Download .
. 10 Download .
.
Join
Download . 10 Download .
()Wait .
Tester Decrementer Incrementer . 10
Decrementer .
counter 5.
Enter Decrementer . counter 5
()Wait .
)if (counter < 5
{
;)Monitor.Wait(this
}
()Wait . CLR .
Pulse .
;)Monitor.Pulse(this
()Pulse CLR .
()Exit
.
;)Monitor.Exit(this
4-24 . counter Monitor
.
4-24
#region Using directives
;using System
;using System.Collections.Generic
;using System.Text
;using System.Threading
#endregion
namespace UsingAMonitor
{
class Tester
{
;private long counter = 0
) (static void Main
{
// make an instance of this class
452
Tester t = new Tester( );
// run outside static Main
t.DoTest( );
}
public void DoTest( )
{
// create an array of unnamed threads
Thread[] myThreads =
{
new Thread( new ThreadStart(Decrementer)
new Thread( new ThreadStart(Incrementer)
};
// start each thread
int ctr = 1;
foreach ( Thread myThread in myThreads )
{
myThread.IsBackground = true;
myThread.Start( );
myThread.Name = "Thread" + ctr.ToString(
ctr++;
Console.WriteLine( "Started thread {0}",
),
)
);
myThread.Name );
Thread.Sleep( 50 );
}
// wait for all threads to end before continuing
foreach ( Thread myThread in myThreads )
{
myThread.Join( );
}
// after all threads end, print a message
Console.WriteLine( "All my threads are done." );
}
void Decrementer( )
{
try
{
// synchronize this area of code
Monitor.Enter( this );
// if counter is not yet 10
// then free the monitor to other waiting
// threads, but wait in line for your turn
if ( counter < 10 )
{
Console.WriteLine(
"[{0}] In Decrementer. Counter: {1}. Gotta Wait!",
Thread.CurrentThread.Name, counter );
Monitor.Wait( this );
}
while ( counter > 0 )
{
long temp = counter;
temp--;
Thread.Sleep( 1 );
counter = temp;
Console.WriteLine(
"[{0}] In Decrementer. Counter: {1}. ",
Thread.CurrentThread.Name, counter );
}}
finally
{
Monitor.Exit( this );
}}
453
454
C#
. While if Decrementer
//if (counter < 10)
while (counter < 5)
Counter . Decrementer 2Thread
455
C#
: .
Wait .
-3-20
Thread.
()Thread.Sleep .
CLR Interlocked .
lock .
()Wait .
456
:
-
Web Web
WebClient
Web Browser
IP DNS
ASP.NET
Internet
Download
Upload
C#
- 09177112161 -
. API ) (Winsock
.
NET. .
WebBrowser
.
.
-1-25 WebClient
URL System.NET.WebClient NET.
. .
URINET. :File: HTTPS:, HTTP .
-1-1-25
WebClient .
. ()DownloadFile .
URI : ) ( .
;)(WebClient Client = new WebClient
;)"Client.DownloadFile("http://www.reuters.com/", "ReutersHomepage.htm
.
()OpenRead . ()OpenRead Stream .
.
;)(WebClient Client = new WebClient
;)"Stream strm = Client.OpenRead("http://www.reuters.com/
-2-1-25 WebClient
()WebClient.OpenRead . ListBox
. #c Windows Forms
ListBox 1listBox DockStyle.Fill .
system.Net System.IO
.
)(public Form1
{
458
InitializeComponent();
System.Net.WebClient Client = new WebClient();
Stream strm = Client.OpenRead("http://www.reuters.com");
StreamReader sr = new StreamReader(strm);
string line;
while ( (line=sr.ReadLine()) != null )
{
listBox1.Items.Add(line);
}
strm.Close();
}
. System.Io StreamReader
1-25 . ReadLine
.
1-25
.)( OpenWrite WebClient
. post . . URI
. accept
. accept hello world newfile.txt
WebClient webClient = new WebClient();
Stream stream = webClient.OpenWrite("ftp://localhost/accept/newfile.txt");
StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.WriteLine("Hello World");
streamWriter.Close();
-3-1-25
UpLoadFile .)( UpLoadData )( UpLoadFile WebClient
UpLoadData
. URI
WebClient client = new WebClient();WebClient client = new WebClient();
client.UploadFile("ftp://www.ourwebsite.com/NewFile.htm",
"C:\\WebSiteFiles\\NewFile.htm");
byte[] image;
// code to initialise image so it contains all the binary data for
// some jpg file
client.UploadData("ftp://www.ourwebsite.com/NewFile.jpg", image);
459
C#
- 09177112161 -
460
HTTP .
. NET.
. WebRequest WebResponse
. HTTP :
HttpWebRequest,
HTTP . GetResponse
HttpWebResponse WebResponse .
HTTP .
)( GetResponse .
;)listBox1.Items.Add("Request Timeout (ms) = " + wrq.Timeout
;)listBox1.Items.Add("Request Keep Alive = " + hwrq.KeepAlive
;)listBox1.Items.Add("Request AllowAutoRedirect = " + hwrq.AllowAutoRedirect
TimeOut 100000 .
) (WebException .
Status WebException .
.
KeepAlive HTTP .
HttpWebRequest . KeepAlive
. true.
AllowAutoRedirect HttpWebRequest .
true .
MaximumAutomaticRedirections HttpWebReques
.
Headers . GetResponse
ListBox .
;("WebRequest wrq = WebRequest.Create("http://www.reuters.com
;()WebResponse wrs = wrq.GetResponse
;WebHeaderCollection whc = wrs.Headers
(++for(int I = 0; I < whc.Count; i
}
461
C#
- 09177112161 -
Credentials WebRequest .
) NetworkCredentials (System.Net
. GetResponse .
;("NetworkCredential myCred = new NetworkCredential("myusername", "mypassword
;wrq.Credentials = myCred
-6-1-25
WebRequest .
.
WebClient.DownloadData WebRequest.GetResponse
) ( . .
()BeginGetResponse ()EndGetResponse . BeginGetResponse
.
. WebResponse
IAsyncResult .
EndGetResponse .
BeginGetResponse . CallBack
IAsyncResult void .
.
EndGetResponse CallBack WebResponse .
()public Form1
}
;()InitializeComponent
;("WebRequest wrq = WebRequest.Create("http://www.reuters.com
;(wrq.BeginGetResponse(new AsyncCallback(OnResponse), wrq
{
(protected void OnResponse(IAsyncResult ar
462
}
;WebRequest wrq = (WebRequest)ar.AsyncState
;(WebResponse wrs = wrq.EndGetResponse(ar
... read the response //
{
WebRequest BeginGetResponse
. . CallBack
IAsyncState IAsyncResult .
-2-25 HTML
NET. .
. HTML Internet
Explorer . NET. IE .
. NET. 2,0 COM IE NET.
. 2,0NET . WebBrowser .
IE Process
System.Diagnostics .
;()Process myProcess = new Process
;"myProcess.StartInfo.FileName = "iexplore.exe
;"myProcess.StartInfo.Arguments = "http://www.wrox.com
;()myProcess.Start
IE .
.
WebBrowser
. WebBrowser .
-1-2-25
Windows From TextBox
WebBrowser . URL
Enter .
2005VS 3-25 .
463
09177112161 - -
C#
35-3
) Enter URL
. WebBrowser (
. -KeyPress1textBox
. WebBrowser Enter
.
;using
;using
;using
;using
;using
;using
;using
System
System.Collections.Generic
System.ComponentModel
System.Data
System.Drawing
System.Text
System.Windows.Forms
namespace CSharpInternet
}
partial class Form1 : Form
}
()public Form1
}
;()InitializeComponent
{
(private void textBox1_KeyPress(object sender, KeyPressEventArgs e
}
(if (e.KeyChar == (char)13
}
;(webBrowser1.Navigate(textBox1.Text
{
{
{
{
464
35-4
-2-2-25 IE
.
. Windows From
LinkLabel . " "!Visit our company web side .
.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
(e
}
;()WebBrowser wb = new WebBrowser
;(wb.Navigate("http://www.wrox.com", true
{
LinkLabel WebBrowser .
WebBrowser.Navigate .
true . false.
-3-2-25 IE
) WebBrowser (
URL . WebBrowser
. .
HTML . DocumentTitleChanged
Text .
465
C#
- 09177112161 -
35-5
IE WebBrowser .
HomeRefresh Stop Forward Back .
ToolBar Button .
5 TextBox 6-25 .
466
6-25
. IE
. buttonForward
buttonBack
buttonHomebuttonRefresh buttonStop .
Anchor Right Top .
buttonStop buttonForward buttonBack .
WebBrowser .
. Stop
. WebBrowser .
.
System
System.Collections.Generic
System.ComponentModel
System.Data
System.Drawing
System.Windows.Forms
;using
;using
;using
;using
;using
;using
namespace CSharpInternet
}
: Form 1partial class Form
}
()1public Form
}
;()InitializeComponent
{
(_DocumentTitleChanged(object sender, EventArgs e1private void webBrowser
}
;().DocumentTitle.ToString1this.Text = webBrowser
{
467
09177112161 - -
C#
;()webBrowser1.GoHome
;()textBox1.Text = webBrowser1.Url.ToString
{
(private void buttonRefresh_Click(object sender, EventArgs e
}
;()webBrowser1.Refresh
{
(private void buttonSubmit_Click(object sender, EventArgs e
}
;(webBrowser1.Navigate(textBox1.Text
{
(private void webBrowser1_CanGoBackChanged(object sender, EventArgs e
}
(if (webBrowser1.CanGoBack == true
}
;buttonBack.Enabled = true
{
else
}
;buttonBack.Enabled = false
{
{
(private void webBrowser1_CanGoForwardChanged(object sender, EventArgs e
}
(if (webBrowser1.CanGoForward == true
}
;buttonForward.Enabled = true
{
else
}
;buttonForward.Enabled = false
{
{
,private void webBrowser1_Navigating(object sender
(WebBrowserNavigatingEventArgs e
}
;buttonStop.Enabled = true
469
C#
- 09177112161 -
{
,private void webBrowser1_DocumentCompleted(object sender
(WebBrowserDocumentCompletedEventArgs e
}
;buttonStop.Enabled = false
{
{
{
.
. WebBrowser . Back
()GoBack WebBrowser
Stop GoForward
Refresh GoHome . IE
.
_Load1Form .
URL submit
.
.
Stop .
Navigating Stop .
,private void webBrowser1_Navigating(object sender
(WebBrowserNavigatingEventArgs e
}
;buttonStop.Enabled = true
{
Stop .
,private void webBrowser1_DocumentCompleted(object sender
(WebBrowserDocumentCompletedEventArgs e
}
;buttonStop.Enabled = false
{
Back Forward
. CanGoBackChanged CanGoForwardChanged
.
(private void webBrowser1_CanGoBackChanged(object sender, EventArgs e
}
(.CanGoBack == true1if (webBrowser
470
}
;buttonBack.Enabled = true
{
else
}
;buttonBack.Enabled = false
{
{
(private void webBrowser1_CanGoForwardChanged(object sender, EventArgs e
}
(.CanGoForward == true1if (webBrowser
}
;buttonForward.Enabled = true
{
else
}
;buttonForward.Enabled = false
{
{
.
. 7-25 .
7-25
-4-2-25 WebBrowser
WebBrowser .
. WebBrowser
URL . WebBrowser
Word ,Excel PDF .
.
471
C#
Word . WebBrowser
Word . 8-25 .
8-25
9-25 Adobe PDF .
9-25
WebBrowser WebBrowser
WebBrowser .
AllowWebBrowser WebBrowser false .
-5-2-25 WebBrowser
WebBrowser
. .
;)(webBrowser1.Print
. WebBrowser
HTML . :
472
;)(WebBrowser wb = new WebBrowser
;)"wb.Navigate("http://www.wrox.com
;)(wb.Print
-6-2-25
WebRequest Stream
. .
()public Form1
}
;()InitializeComponent
;()System.Net.WebClient Client = new WebClient
;("Stream strm = Client.OpenRead("http://www.reuters.com
;(StreamReader sr = new StreamReader(strm
;string line
( while ( (line=sr.ReadLine()) != null
}
;(.Items.Add(line1listBox
{
;()strm.Close
WebBrowser .
Document_Completed .
,private void webBrowser1_DocumentCompleted(object sender
(WebBrowserDocumentCompletedEventArgs e
}
;buttonStop.Enabled = false
;()textBox2.Text = webBrowser1.DocumentText.ToString
{
TextBox WebBrowser .
TextBox.
DocumentText WebBrowser
. DocumentStream
Stream . TextBox 10-25
.
473
C#
- 09177112161 -
35-10
-3-25 Web
WebRequest WebResponse . 11-25
.
11-25
.
WebRequest WebResponse .
.
) http, FTP, SMTP (
.
. ()WebRequest.Create HttpWebRequest
GetResponse HttpWebResponse .
.
.
HTTPSFTP HTTP FTP . NET. 2,0
. API
.
474
-1-3-25
IP URI
URI
URI UriBuider System URI UriBuider .
URI URI URI
. URI URI .
Uri MSPage = new
;)"Uri("http://www.Microsoft.com/SomeFolder/SomeFile.htm?Order=true
. URI
.
// Order=true
// SomeFolder/SomeFile.htm
// http
UriBulider . URI
. - . URI .
Uri MSPage = new
;)"UriBuilder("http", "www.Microsoft.com", 80, "SomeFolder/SomeFile.htm
URI .
;()UriBuilder MSPage = new UriBuilder
;"MSPage.Scheme ="http
;"MSPage.Host = "www.Microsoft.com
;MSPage.Port = 80
;"MSPage.Path = "SomeFolder/SomeFile.htm
UriBuider URI URI
.
;Uri CompletedUri = MSPage.Uri
-2-3-25 IP DNS
IP ) DNS ( .
. IP
. IP
. IP .
IP .
DNS . DNS IP
475
C#
- 09177112161 -
. IP DNS .
DNS . .
DNS IP .
IP .
.
-3-3-25 NET. IP
NET. IP .
IPAddress
IP . ()GetAddressBytes
)( ToString IPAddress . Parse
ToString . IPAddress .
;)"IPAddress ipAddress = IPAddress.Parse("234.56.78.9
;)(byte[] address = ipAddress.GetAddressBytes
;)(string ipString = ipAddress.ToString
address ipString
" "234,56,78,9 .
IPAddress . LoopBack
Broadcast
.
."127,0,0,1The following line will set loopback to " //
.the loopback address indicates the local host //
;()string loopback = IPAddress.Loopback.ToString
."255,255,255,255The following line will set broadcast address to " //
the broadcast address is used to send a message to all machines on //
IPHostEntry .
HostName AddressList IPAddress
. DNSLockupResolver IPHostEntry ..
DNS IP DNS .
()GetHostByAddress(), Resolve ()Resolve
GetHostByAddress IP .
IPHostEntry .
;)"IPHostEntry wroxHost = Dns.Resolve("www.wrox.com
;)"IPHostEntry wroxHostCopy = Dns.GetHostByAddress("208.215.179.178
IPHostEntry wrox.com .
476
DNS
-4-3-25 DNSLookup
DNS IP DNS . 12-25 .
12-25
DNS . Resolve
()Dns.Resolve IPHostEntry
IP .
DNS DNS .
DNSLookup #c .
btnResolve ,txtBoxInput txtBoxHostName listBoxIPS .
btnResolve Form .
(void btnResolve_Click (object sender, EventArgs e
}
try
}
;(IPHostEntry iphost = Dns.Resolve(txtBoxInput.Text
(foreach (IPAddress ip in iphost.AddressList
}
;()string ipaddress = ip.AddressFamily.ToString
;(listBoxIPs.Items.Add(ipaddress
" + ip.ToString
"(;(()listBoxIPs.Items.Add
{
;txtBoxHostName.Text = iphost.HostName
{
(catch(Exception ex
477
C#
- 09177112161 -
}
+ " MessageBox.Show("Unable to process the request because
"+ "the following problem occurred:\n
;("ex.Message, "Exception occurred
{
{
. DNS
.
IPHostEntry AddressList IP
foreach . IP
()IPAddress.AddressFamily.ToString .
-4-25
System.Net System.Net.Socket
. System.Net .
TCP/IP
.
WebClient .
UpLoadFile .
WebRequest URI .
WebResponse . .
WebRequest WebResponse .
NetworkCredentials
WebBrowser
.
WebBrowser .
WebBrowser HTML .
UriBuider URI .
IPAddress .
IPHostEntry .
478
TCP,UDP
TCP
UDP
NewsTicker UDP
-1-26
1 . .
.
" ) LAN- WAN ( ) cell Phone- WireLess
C#
- 09177112161 -
.
TCP/IP ARPA TCP/IP .
) TCP IP
( . NET. Sytem.Net.Sockets.Socket .
IP .
.
. Berkeley Sockets . 1-26
TCP/IP .
1-26
:
-
:1 IP . .
:2 .
) 2-26 ( . IP
.
:3 .
.
2-26
Raw
Datagram
Stream
480
. .
.
. 2-26 .
-1-1-26 TCP
TCP . TCP .
. ) ( . 3-26 .
) .(4-26
" ) ( . )
(.
3-26
4-26
) ( . 5-26 .
5-26
TCP IP IP .- Best-effort .
" Best-effort .
.
TCP . TCP .
. " .
TCP .
. 1 .
Timeout
481
C#
- 09177112161 -
UDP . .
-2-1-26 UDP
UDP Best-effort- . UDP .
.
) 7-26 ( .
. Best-effort .
. 1 2 2 1
) 8-26 (.
. " ) -26
9 (.
7-26
8-26
482
9-26
. :
-
UDP : TCP . .
.
. .
" .
.
20 . 16
16 .
-
Besteffort . ping
.
. Ping
.
" UDP SNMP ,DNS .
UDP . IP ) 10-26
( . IP 224,0,0,1 239,255,255,255 .
.
10-26
483
C#
- 09177112161 -
.
IP . .
.
. .
-3-1-26
.
. 16
0 65535 . 0 1023 ) )MAIL25( HTTP(80
) Telnet(23 .
.
. .
) 11-26 (.
11-26
11-26 .
.
.
. .
.
WEB .
. Net
.
484
-4-1-26 System.Net
System.Net.Sockets .
System.Net .
System.Net .
WebRequest WebResponse .
. HTTP : ) HttpWebRequest
(HttpWebResponse //:file ) FileWebRequest .(FileWebResponse
IP .
1-26 .
1-5
IPAddress
IP .
IPEndPoint
.
IP .
-5-1-26 System.Net.Sockets
" .
Socket . .
. 2-26 .
2-26
Socket
NetworkStream
TcpClient
TCP .
TcpListener
TCP
.
UdpClient
UDP .
. TCP .
-2-26 TCP
.
. .
485
C#
- 09177112161 -
)
( . 12-26
12-26
.
LAN .
.
. .
. . 13-26
.
)
( . 14-26 .
.
.
. URL
. URL GET .
HTML .
13-26
14-26
486
.
" "Hello World .
GET, EXIT . :
)(establish tcp connection to the server
)(accept connection
>GET<CRLF
>"Hello World !"<CRLF
>EXIT<CRLF
>BYE<CRLF
)(close connection
)(close connection
c:
s:
c:
s:
c:
s:
c:
s:
C S <CRLF> . ENTER .
HTTP SMTP .
-1-2-26 .Net
. System.Net.Sockets.TcpClient
.System.Net.Sockets.TcpListener TcpClient
. .
.
// connect client to the server 127.0.0.1:8080
;) TcpClient client = new TcpClient ( "127.0.0.1", 8080
// get the network stream for reading and writing something
// to the network
;)( NetworkStream ns = client.GetStream
// read/write something from/to the stream
// disconnect from server
;)( client.Close
. . TcpListener
.
. .
// create a listener for incoming TCP connections on port 8080
;) TcpListener listener = new TcpListener ( 8080
;)( listener.Start
// wait for and accept an incoming connection
487
C#
-2-2-26
. TcpHelloWorldServer .
." .
) 15-26 ( 18-26 . ( )Main .
15-26
;using System
;using System.IO
;using System.Net.Sockets
8080 . AcceptSocket
. .
. AcceptSocket
. NetworkStream .
System.Net.Sockets .NetworkStream .
. StreamReader .
System.IO . .
()ReadLine . .
\ n\r .
. .
17-26 .
17-26
;bool loop = true
) while ( loop
{
// read a line until CRLF
;)( string command = r.ReadLine
;string result
Console.WriteLine ( "executing remote command: " +
;) command
) switch ( command
{
case "GET":
488
;"! result = "Hello World
;break
// finish communication
case "EXIT":
;"result = "BYE
;loop = false
;break
// invalid command
default:
;"result = "ERROR
;break
}
) if ( result != null
{
;) Console.WriteLine ( "sending result: " + result
// add a CRLF to the result
;"result += "\r\n
// convert data string to byte array
( Byte[] res = System.Text.Encoding.ASCII.GetBytes
;) )( result.ToCharArray
// send result to the client
;) s.Send ( res, res.Length, 0
}
}
-3-2-26
. : )) UI
.
TcpRemoteCommandProcessor . 19-26 25-26
Base.cs Base.cs Base.dll .
19-26 .
19-26
;using System
;using System.IO
;using System.Net.Sockets
.
. .
) 20-26 (.
20-26
public interface CommandProcessor
{
// execute a command and return the result
// if the return value is false the command processing loop
// should stop
;) bool Execute ( string command, ref string result
}
489
C#
- 09177112161 -
TcpRemoteCommandProcessor .
: ()Close .()Execute .
Hold " .
()Close .
Release .
. .
.
. 21-26
.
21-26
// remote host
;private string host = null
// remote port
;private int port = -1
// connection mode
;private bool releaseConnection = false
// communication interface
;private TcpClient client = null
// outgoing data stream
;private NetworkStream outStream = null
// ingoing data stream
;private StreamReader inStream = null
22-26 . :
. True Release
Hold . Hold "
." .
22-26
public TCPRemoteCommandProcessor ( string host, int port,
) bool releaseConnection
{
// add parameter checking here
;this.host = host
;this.port = port
;this.releaseConnection = releaseConnection
) if ( !this.releaseConnection
{
Console.WriteLine ( "connecting to " + this.host + ":" +
;) "this.port + "...
;) this.client = new TcpClient ( this.host, this.port
;)( this.outStream = this.client.GetStream
;) this.inStream = new StreamReader ( this.outStream
Console.WriteLine ( "connected to " + this.host + ":" +
;) this.port
}
}
.
23-26
)( public void Close
{
) if ( this.client != null
{
;)( this.client.Close
Console.WriteLine ( "connection closed: " + this.host +
;) ":" + this.port
490
}
}
. TcpHelloWorldClient .
. TcpHelloWorldClient
GET . TcpCommandProcessor
. EXIT .
25-26
using System;
using System.IO;
using System.Net.Sockets;
public class TCPHelloWorldClient
{
public static void Main ()
{
Console.WriteLine ( "initializing client..." );
TCPRemoteCommandProcessor proc = new
TCPRemoteCommandProcessor ( "127.0.0.1", 8080, false );
string result;
Console.WriteLine ( "requesting..." );
proc.Execute ( "GET", ref result );
Console.WriteLine ( "result: " + result );
Console.WriteLine ( "closing connection..." );
proc.Execute ( "EXIT", ref result );
proc.Close ();
Console.Write ( "press return to exit" );
Console.ReadLine ();
}
491
C#
09177112161 -}
-4-2-26
2005Vs
. TcpHelloWorldServer .
26-26 .
TcpHelloWorldClient.exe .
27-26 .
26-26
27-26
28-26 . .
UDP .
28-26
-3-26 UDP
UDP" .
.
-1-3-26 NET
TCP UDP . ) (P2P.
System.Net.Sockets.UdpClient .
UDP . "
UDP .
. UdpClient . .
492
()Send .
UDP . UdpClient
()Receive . dummy
null .
// bind client to local port where it receives data
;) UdpClient client = new UdpClient ( 8081
// create a byte array containing the characters of
"// the string "a request
( Byte[] request = System.Text.Encoding.ASCII.GetBytes
;) )( "a request".ToCharArray
// send request to the server
;) client.Send ( request, request.Length, "127.0.0.1", 8080
// create a dummy endpoint
;IPEndPoint dummy = null
// receive something from the server
;) byte[] response = client.Receive ( ref dummy
// do something with the response
// unbind the client
;)( client.Close
NET. .
-2-3-26
. ()Main . .
UdpClient . 29-26 ()Main .
29-26
;) "Console.WriteLine ( "initializing server
;) UdpClient server = new UdpClient ( 8080
UDP . .
UDP . IP UDP
IP . IP IP #C
API ) (NET.
) ( . :
IP ADDRESS " : " PORT " : " COMMAND
493
09177112161 - -
C#
// command execution
31-26 . TcpHelloWorldServer
.
31-26
// convert data string to byte array
Byte[] d = System.Text.Encoding.ASCII.GetBytes (
result.ToCharArray () );
// send result to the client
server.Send ( d, d.Length, remoteClientHost,
remoteClientPort );
. . TcpHelloWorldServer
-3-3-26
. UdpHelloWorldClient.CS UdpHelloWorldClient
.( ) TcpHelloWorldClient
32-26 . BASE.CS UdpCommandProcessor
.
32-26
UDPRemoteCommandProcessor proc = new UDPRemoteCommandProcessor ( 8081, "127.0.0.1", 8080 );
IP . 8081
.
TcpCommandProcessor . UdpCommandProcessor
33-26 ) .()Execute)( Close :
.(
33-26
// the local port where the processor is bound to
private int localPort = -1;
// the remote host
private string remoteHost = null;
// the remote port
private int remotePort = -1;
// communication interface
private UdpClient client = null;
. UDP
34-26
public UDPRemoteCommandProcessor ( int localPort,
string remoteHost, int remotePort )
{
// add parameter checking here
this.localPort = localPort;
this.remoteHost = remoteHost;
this.remotePort = remotePort;
this.client = new UdpClient ( localPort );
}
494
. TcpCommandProcessor )( Execute
. IP .( UDP)
. UDP 36-26 .
36-26
public bool Execute ( string command, ref string result )
{
// add parameter checking here
bool ret = true;
Console.WriteLine ( "executing command: " + command );
// build the request string
string request = "127.0.0.1:" + this.localPort.ToString ()
+ ":" + command;
Byte[] req = System.Text.Encoding.ASCII.GetBytes (
request.ToCharArray () );
client.Send ( req, req.Length, this.remoteHost,
this.remotePort );
// we don't need an endpoint
IPEndPoint dummy = null;
// receive datagram from server
byte[] res = client.Receive ( ref dummy );
result = System.Text.Encoding.ASCII.GetString ( res );
ret = !result.Equals ( "BYE" );
return ret;
}
-4-3-26
. UdpHelloWorldClient.CS UdpHelloWorldServer.CS
. 39-26 38-26 37-26 .
.
37-26
38-26
39-26
. UDP
495
C#
- 09177112161 -
-4-26 UDP
1 .
. .
. UDP .
. IP .
IP .
.
. .
) 40-26 (.
40-26
.
marquee ) 41-26 (.
41-26
-1-4-26 NET
UDP System.Net.Sockets.UdpClient .
()UdpClient.JoinMultiCastGroup . UDP
. .
UdpClient . ()JoinMultiCastGroup
. IP ." IPEndPoint
. IPEndPoint IP .
// create a peer bound to a local port
;) UdpClient peer = new UdpClient ( LOCAL_PORT
// create the group IP address
;) IPAddress groupAddress = IPAddress.Parse ( GROUP_IP
// add the peer to the group
;) peer.JoinMulticastGroup ( groupAddress
News ticker
496
// create an end point for sending data to the group
IPEndPoint groupEP = new IPEndPoint ( groupAddress,
GROUP_PORT );
. UDP
// send data to the group, d is a byte array
peer.Send ( d, d.Length, groupEP );
// receiving data from the group
IPEndPoint dummy = null;
byte[] d = peer.Receive ( ref dummy );
.
. UdpClient . Base.cs UDPPeer
.
)( Close . UDP IP .
.)( Send )( Receive
.( 42-26 )
42-26
// udp peer
private UdpClient server = null;
// multicast group IP address
private IPAddress groupAddress = null;
// multicast group endpoint (IP address and port)
private IPEndPoint group = null;
. UDP
IPAddress .( 44-26 )
group . groupAddress . IP
. " IPEndPoint
44-26
public UDPPeer ( int localPort, string groupIP,
int groupPort ) : this ( localPort )
{
// add parameter checking here
Console.WriteLine ( "adding UDP server to multicast " +
"group, IP=" + groupIP + ", port=" + groupPort + "...");
this.groupAddress = IPAddress.Parse ( groupIP );
this.group = new IPEndPoint ( this.groupAddress,
groupPort );
this.server.JoinMulticastGroup ( this.groupAddress );
Console.WriteLine ( "UDP server added to group" );
}
497
09177112161 - -
C#
. .)( Close
.( 45-26 )( ) UdpClient.Close
45-26
public void Close ()
{
if ( this.groupAddress != null )
this.server.DropMulticastGroup ( this.groupAddress );
this.server.Close ();
}
.( 46-26 ) ()Receive
.
46-26
public String Receive ()
{
IPEndPoint dummy = null;
// receive datagram
byte[] data = this.peer.Receive ( ref dummy );
return new System.Text.ASCIIEncoding ().GetString (
data );
}
-2-4-26
UDPNewsServer . UDPpeer
. UDPNewsServer.CS
:
.
). System.Windows.Forms.Form
.( 48-5
48-26
// local port where the UDP server is bound to
private const int LOCAL_PORT = 8080;
// multicast group IP address
private const string GROUP_IP = "225.0.0.1";
// multicast group port
private const int GROUP_PORT = 8081;
// UDP server
private UDPPeer server = null;
// a thread for sending new continuously
private Thread serverThread = null;
// a data field for typing in a new message
498
;private TextBox text = null
// a button for setting the new message
;private Button setButton = null
// the news message
;"" = private string news
49-26 UI . Send
.
()OnSet . ()OnClose .
()Run .
49-26
)( public UDPNewsServer
{
// UI components initialization
// add an event listener for click-event
;) this.setButton.Click += new System.EventHandler ( OnSet
// add an event listener for close-event
;) this.Closed += new System.EventHandler ( OnClosed
// create communication components
this.server = new UDPPeer ( LOCAL_PORT, GROUP_IP,
;) GROUP_PORT
// start communication thread
( this.serverThread = new Thread
;) ) new ThreadStart ( Run
;)( this.serverThread.Start
;) "Console.WriteLine ( "initialization complete
}
. ) 50-26
( . news
. ()Sleep
.
50-26
// sending thread
)( public void Run
{
) while ( true
{
) ) "" ( if ( !this.news.Equals
{
;) Console.WriteLine ( "sending " + this.news
;) this.server.Send ( this.news
}
// wait one second
;) Thread.Sleep ( 1000
}
}
" . Closed .
()Abort ) ()Join
( . ()Close UDPPeer ) 52-26 (.
52-26
) public void OnClosed ( Object sender, EventArgs e
{
;) "Console.WriteLine ( "server shut down...
499
C#
-3-4-26
: UDP .
UDPMultiCastClient base.cs .
.
chat .
. .
. .
. 53-26 .
: ticker .
. ticker .
UDPMultiCastClient .
()Notify ()SetNows .
()Notify 54-26 . Base.CS .
. .
53-26
54-26
;) public delegate void Notify ( string text
: System.Net.Sockets.Socket .
DLL Socket . ()Accept
()Receive ()BeginAccept ()EndAccept ()BeginRecieve ()EndRecive
500
. ()BeginAccept .
AsyncCallback .
UDPMultiCastClient . . UDP
. ()Run
()Close . .
) 55-26 (.
55-26
// notification delegate
;private Notify notify = null
// communication interface
;private UDPPeer peer = null
// receiving thread
;private Thread clientThread = null
Notify UDP IP .
) .(56-26
56-26
public UDPMulticastClient ( string groupIP, int groupPort,
) Notify notify
{
// add parameter validation here
Console.WriteLine ( "initializing UDP multicast " +
"client, group=" + groupIP + ", port=" + groupPort +
;) ""...
;this.notify = notify
// create communication components
this.client = new UDPPeer ( groupPort, groupIP,
;) groupPort
// start listener thread
( this.clientThread = new Thread
;) ) new ThreadStart ( Run
;)( this.clientThread.Start
;) "Console.WriteLine ( "UDP multicast client initialized
}
()Run .
Notify) .(57-26
57-26
)( public void Run
{
) while ( true
;) )( this.notify ( this.peer.Receive
}
()Close . ()Close
UDP ) .(58-26
58-26
)( public void Close
{
;)( this.clientThread.Abort
;)( this.clientThread.Join
;)( this.peer.Close
}
UDP . .
System.Windows.Forms.Form UDPNewsCleint
UDPNewsClient.CS . . .
501
09177112161 - -
C#
)( OnClosed .
()SetNews )( RunTicker " .)( Closed
UDPMultiCastClient )( Notify
. 59-26 .
59-26
// multicast group IP address
private const string GROUP_IP = "225.0.0.1";
// multicast group port
private const int GROUP_PORT = 8081;
// communication interface
private UDPMulticastClient client = null;
// ticker thread
private Thread tickerThread = null;
// new messages
private TextBox text = null;
// default news displayed at the beginning
private string news = "Please wait...";
.(61-26 ) Closed
. ticker
61-26
public void OnClosed ( Object sender, EventArgs e )
{
Console.WriteLine ( "client shut down" );
this.client.Close ();
this.tickerThread.Abort ();
this.tickerThread.Join ();
Application.Exit ();
}
. 500 ticker
.)( Notify .
.
62-26
public void RunTicker ()
{
// initialze the textbox with the default text
this.text.Text = " -+-+- " + this.news + " -+-+- " +
this.news + " -+-+- ";
while ( true )
{
string data = this.news + " -+-+- ";
// repeat as long as there are characters in the data string
while ( !data.Equals ( "" ) )
{
502
// wait 500 milliseconds
Thread.Sleep ( 500 );
// remove the first character from the text field and add the
// first character of the data string
this.text.Text = this.text.Text.Substring ( 1 ) +
data[0];
// remove the first character from the data string
data = data.Substring ( 1 );
}
}
}
// notification method, used by multicast client
public void SetNews ( string news )
{
this.news = news;
}
-4-4-26
. UDPNewsServer.exe UDPNewsClient.exe
.
65-26 set 64-26 63-26
.
63-26
64-26
65-26
503
#C
:
-
Socket
TCP UDP
Socket
Socket API WinSock . Socket :
.1 Socket .
.2 Socket )( Bind 1 .
.3 Socket Connect() .
.4 Socket Listen() .
.5 )( Send )( Receive TCP )( SendTo
)( ReceiveFrom UDP .
.6 ()ShutDown .
.7 )( Close .
;)public Socket(AddressFamily,SocketType,ProtocolType
Socket . AddressFamily
SocketType ProtocolType . AddressFamily
SocketType InterNetwork TCP Stream UDP Dgram ProtocolType TCP
TCP UDP UDP .
.
;)public void Connect(EndPoint remoteEP
.
;)public object GetSocket(SocketOptionLevel, SocketOptionName
;)][public void GetSocketOption (SocketOptionLevel ,SocketOptionName ,byte
;)public byte[] GetSocketOption (SocketOptionLevel ,SocketOptionName ,int
Socket . SocketOptionLevel
SocketOptionName . SocketException ObjectDisposedException
.
;)public void Listen(int backlog
Socket TCP
backlog . .
5 . SocketException
ObjectDisposedException .
;)public bool Poll(int microSeconds,SelectMode mode
End point
505
09177112161 - -
C#
. .
. SelectMode .
SelectWrite
SelectMode. SelectMode.SelectRead
. SelectMode.SelectError
public
public
public
public
public
int
int
int
int
int
SocketFlags . buffer
. .
ObjectDisposedException SocketExceptionArgumentOutOfRange
ArgumentNullException
.
void
1
IList
Select(IList
readableList,IList
WriteableList,IList
errorList,
int
Ilist . Socket
.( ) Socket
int
int
int
int
Send(byte[]
Send(byte[]
Send(byte[]
Send(byte[]
buffer);
buffer,socketFlags flags);
buffer,int length.socketFlags flags);
buffer,int offset,int length, SocketFlags flags);
SocketFlags . buffer
. .
public int SendTo (byte[]
public int Sendto (byte[]
public int SendTo (byte[]
public int SendTo (byte[]
EndPoint remotEP);
Container
506
UDP buffer .
SocketFlags .
.
public void SetSocketOption(SocketOptionLevel optionLevel
;),SocketOptionName optionName, byte[] optionValue
public void SetSocketOption(SocketOptionLevel optionLevel
;),SocketOptionName optionName, int optionValue
public void SetSocketOption(SocketOptionLevel optionLevel
;),SocketOptionName optionName, object optionValue
Socket
;)Public void Shutdown(SocketShutdown how
. SocketShutdown
) (.
Socket I/O .
};LocalEndPoint{get
Public EndPoint
Socket .
};Public EndPoint RemoteEndPoint{get
SocketOptionLevel
:
SocketOptionLevel .
SocketOptionLevel ()Socket.SetSocketOption ()Socket.GetSocketOption.
:
:IP Socket IP .
:Socket Socket .
:Tcp Socket TCP .
:Udp Socket UDP .
SocketOptionName
:
SocketOptionLevel Socket
()Socket.SetSocketOption ()Socket.GetSocketOption .
:
NET. 1-1-27 .
507
C#
- 09177112161 -
SocketFlags
:
SocketFlags
Socket . Socket
SocketFlags SocketFlags.None .
:
:DontRoute .
:MaxIOVectorLength WSABUF
.
:None .
:OutOfBand out-of-band .
:Partial
:Peek .
3-1 .
SocketOptionName
AcceptConnection
Boolean
01
Broadcast
Boolean
01
ExclusiveAddressUs
e
Boolean
01
KeepAlive
Boolean
01
alive
MaxConnections
Int32
OutOfBandInline
Boolean
01
ReceiveBuffer
Int32
ReceiveLowWater
Int32
ReceiveTimeOut
Int32
SendLowWater
Int32
SocketOptionLevel
()Listen
. .
.
keep .
()Socket.Listen .
out-of-band
.
Receive
508
SendTimeOut
Int32
Type
Int32
SocketType
SocketOptionLevel.Tcp
BsdUrgent
Boolean
01
Expedited
Boolean
01
NoDelay
Boolean
01
SocketOptionName
SocketOptionLevel.Udp
ChecksumCoverage
Boolean
01
NoChecksum
Boolean
01
UDP
AddMembership
MulticastOption
Group address, .
AddSourceMembershi
p
IPAdress
Group address
BlockSource
Boolean
01
DropMembership
MulticastOption
Group address, .
DropSourceMembersh
ip
IPAddress
Group address
IpTimeToLive
Int32
255-0
.IP
UnblockSource
Boolean
01
UseLoopBack
Boolean
01
.
SocketOptionLevel.IP
interface
.
interface
.
.
SocketException
:
Exception .
:
};public override int ErrorCode{get
ErrorCode . SocketException
.
. ) 2WinSock ( .
};Public virtual string Message {get
.
509
09177112161 - -
C#
TCP
TcpEchoClientSockets.cs
using
using
using
using
using
System;
System.Text;
System.IO;
System.Net.Sockets;
System.Net;
class TcpEchoClientSocket{
static void Main(string[] args){
if((args.Length<2)||(args.Length>3)){//Test for cortrect # of args
throw new ArgumentException("Parameters: <server> <Word> [<Port>]");
}
String server=args[0]; //Server name or IP address
//Convert input String to bytes
byte[] byteBuffer=Encoding.ASCII.GetBytes(args[1]);
//Use port argument if supplied, otherwise default to 7
int servPort=(args.Length==3)? Int32.Parse(args[2]):7;
Socket sock=null;
try{
//Create a TCPsocket instance
sock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//Creates server IPEndPoint instance. We assume Resolve returns
//at least one address
IPEndPoint serverEndPoint=new IPEndPoint(Dns.Resolve(server).AddressList[0],servPort);
//Connect the socket to server on specified port
sock.Connect(serverEndPoint);
Console.WriteLine("Connected to server sending echo string");
//Send the encode string to server
sock.Send(byteBuffer,0,byteBuffer.Length,SocketFlags.None);
Console.WriteLine("Sent {0} bytes to server..",byteBuffer.Length);
int totalBytesRcvd=0;
int bytesRcvd=0;
//Bytes received in last read
//Receiev the same string back from the server
while(totalBytesRcvd<byteBuffer.Length){
if((bytesRcvd=sock.Receive(byteBuffer,totalBytesRcvd,byteBuffer.LengthtotalBytesRcvd,SocketFlags.None))==0){
Console.WriteLine("Connection closed prematurely");
Break;
}
totalBytesRcvd+=bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server:
{1}",totalBytesRcvd,Encoding.ASCII.GetString(byteBuffer,0,totalBytesRcvd));
} catch(Exception e){
Console.WriteLine(e.Message);
}finally{
sock.Close();
}
}
}
Socket -2-1-27
. Socket TCP
. :Socket .1
.)( Bind :Socket )( Bind .2
510
. Socket
.)( Send )(Receive :
.Socket )( Close :
.Socket )(Close : .5
TCP
TcpEchoServerSocket.cs
using System;
//For Console, Int32, ArgumentException , Environment
using System.Net; //For IPAddress
using System.Net.Sockets; //For TcpListener, TcpClient
class TcpEchoServerSocket{
private const int BUFSIZE=32;
511
C#
09177112161 -}
;)Console.WriteLine("echoed {0} bytes.",totalBytesEchoed
Client.Close();// Close the socket. We are done with this client
{)} catch(Exception e
;)Console.WriteLine(e.Message
;)(Client.Close
}
}
}
}
-3-1-27
TCP/IP
. RFC 1122 1123 .
. .
. TcpListtener UdpClient
. Tcpclient
). (3-2
-3-2 TcpClient
LingerState
Nodelay
.
.
ReceiveBufferSize
ReceiveTimeOut
.
TcpClient
) (.
SendBufferSize
SendTimeOut
.
TcpClient
.
Socket . )(GetSocketOption
)( SetSocketOption Socket . overload
.
. SocketOptionName
. SocketOptionName 3-1 .
. www.msdn.microsoft.com .
SocketOptionLevel TCP .IP
SocketOptionLevel 3-1 .
512
( TcpClient )
Protected . Protected Socket
. Socket
Receive()
. SocketOptionName.ReceiveTimeout UDP
: 8-3
. echo .1
5 . 3 Receive() .2
.
. .3
: Socket
UdpClient Socket
Socket UdpClient.Client . Socket
. UdpClient protected
. UDP Socket
UDP
UdpEchoClientTimeoutSocket
using
using
using
using
class UdpEchoClientTimeOut{
private const int TIMEOUT=3000; //Resend timeout (milliseconds)
private const int MAXTRIES=5; //Maximum retransmissions
static void Main(string[] args){
if((args.Length<2)||(args.Length>3)){//Test for cortrect # of args
throw new ArgumentException("Parameters: <server> <Word> [<Port>]");
}
String server=args[0]; //Server name or IP address
//Use port argument if supplied, otherwise default to 7
int servPort=(args.Length==3)? Int32.Parse(args[2]):7;
//Create socket that is connected to server on specified port
Socket sock=new
Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
//Set the receive timeout for this socket
sock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeOut,TIME
OUT);
IPEndPoint remoteIPEndPOint =new
IPEndPoint(Dns.Resolve(server).AddressList[0],servPort);
513
09177112161 - -
C#
-4-1-27
. Send() SendTo() SocketFlags
. Receive() Send()
. SocketFlags.Peek .
ReceiveFrom() Receive() peek
.
.
. .
.
: SocketFlags
,Socket
;(ProtocoleType.Tcp
Bind and/or Connect, create buffer//
.
.
514
.
Peek at the data without dequeuing it from the network buffer//
len = s.Receive(buf, 0, buf.Length, SocketFlags.Peek
;(int
This Receive will return (at least) the same data as the prior//
Receive, but this time it will be bequeued from the network buffer//
= s.Receive(buf, 0, buf.Length, SocketFlags.None
;(Len
I/O-5-1-27
I/O . )(Read
()Receive )( ReceiveFrom . )(
)( ()Send Write )( SendTo . )( ()AcceptSocket Accept
)( AcceptTcpClient Socket TcpListener .
. .
. .
. UDP
.
:
.1 I/O
.2
5-1 .
I/O
I/O
.
5-1 .
I/O
Socket
.1 )( Accept .
.2 Acctept )( Poll )( Select .
.1 )( Pending true AcceptSocket()
)( AcceptTcpClient .
TcpListener
Socket
.1 )( Connect .
.2 )( Connect )( Poll )( Select .
Socket
.1 )( Send )( SendTo .
515
C#
- 09177112161 -
Socket
.1 )( Receive )( ReceiveFrom
.
.2 )( Receive )( ReceiveFrom )( Poll )( Select
.
.3 )( Receive )( ReceiveFrom ReceiveTimeOut
.
.4 > 0Available )( Receive )( ReceiveFrom
.
TcpClient
.1 )( Read ReceiveTimeOut
.
.2 DataAvailable True )( Read
TcpClient ) Length NetworkStream
(.
-6-1-27 I/O
.
I/O I/O
I/O . I/O
.
I/O .
TcpClient DataAvailable NetworkStream
. true false :
client = new TcpClient (server, port
netstream = client. GetStream
;(TcpClient
;()NetworkStream
:
(netstream.DataAvailable
len = netstream.Read(buf,0,buf.Length
}(If
;(int
{ } else
No data available, do other processing//
516
{
TcpListener )( AcceptTcpClient )( AcceptSocket
)( Pending .
)( Pending true false :
listener = new TcpListener(ipadder , port
;(TcpListener
;()Listener.Start
.
.
(listener.pending
}(()If
;()TcpClient=listener.AcceptTcpClient
.
.
{}else
connections pending at this time
;(".Console.WriteLine("no
{
,Socket
;(ProtocolType.Tcp
;(sock.Connect(serverEndPoint
:
}(If(sock.Available>0
we have data to read//
;(sock.Recrive(buf,buf.Length,0
:
{}else
data available to read at this time
;(".Console.WriteLine("no
{
-7-1-27
I/O I/O .
I/O .
UdpEchoClientTimeOutSocket.cs
. ReceiveFrom
. Socket
517
C#
09177112161 - . SocketOption.SendTimeOut
SocketOption.ReceiveTimeOut :
Socket sock=new Socket(AddressFamily.InterNetWork,SocketType.Stream,
;)ProtocolType.Tcp
.
.
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeOut,3000);//set a 3 second timeout on
)(send()/sendTo
SocketException
ErrorCode ) 10060 ( .
)( Poll Socket Poll() . :
mode .
.
)( Poll . mode
SelectMode SelectWrite SelectRead
SelectError . Poll() true
false
:
//Block for 1 second waiting for data to read or incoming connections
{))If(sock.Poll(1000000,SelectMode.SelectRead
//Socket has data to read or an incoming connection
{}else
//no data to read or incoming connections
}
I/O .
.
)( Select Socket I/O.
)( Write )( Send TCP
.
.
.
Socket
. ) ( C #
.
518
echo
TIMELIMIT .
. TIMELIMIT
.
Echo
TcpEchoServerTimeout.cs
using System;
//For Console, Int32, ArgumentException , Environment
using System.Net; //For IPAddress
using System.Net.Sockets; //For TcpListener, TcpClient
class TcpEchoServerTimeOut{
private const int BUFSIZE=32; //Size of receive buffer
private const int BACKLOG=5; //Outstanding connection queue max size
private const int TIMELIMIT=10000; //Default time limit (ms)
static void Main(string[] args){
if(args.Length>1)//Test for correct # of args
throw new ArgumentException("Parameters:[<Port>]");
int servPort=(args.Length==1)? Int32.Parse(args[0]):7;
Socket server=null;
try{
//Create a socket to accept client connections
server=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Any,servPort));
server.Listen(BACKLOG);
}catch (SocketException se){
Consol.WriteLine(se.ErrorCode+":"+se.Message);
Environment.Exit(se.ErrorCode);
}
byte[] rcvBuffer=new byte[BUFSIZE];//Receive buffer
int bytesRcvd;
//Received byte count
int totalBytesEchoed=0;
for(;;){//run forever, accepting and servicing connections
Socket client=null;
try{
client=server.Accept(); //Get client connection
DateTime starttime=DateTime.Now;
//Set the ReceiveTimeout
client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,TI
MELIMIT);
Console.Write("Handling client at"+ client.RemoteEndPoint+"-");
//Receive until closes connection, indicated by 0 return value
totalBytesEchoed=0;
while((bytesRcvd=client.Receive(rcvBuffer,0,rcvBuffer.Length,SocketFlags.None))>0){
client.Send(rcvBuffer, 0, SocketFlags.None);
totalBytesEchoed+=bytesRcvd;
//Check elapsed time
519
C#
- 09177112161 -
;TimeSpan elapsed=DateTime.Now-starttime
{)if(TIMELIMIT-elapsed.TotalMilliseconds<0
Console.WriteLine("Abortig client, timelimit"+ TIMELIMIT+ "ms exceeded, echoed "+
;)"totalBytesEchoed+ " bytes
;)(client.Close
;)throw new SocketException(10060
}
//Set the ReceiveTimeOut
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,int(TIMELIMIT;))elapsed.TotalMilliseconds
}
;)Console.WriteLine("echoed {0} bytes.", totalBytesEchoed
;)(client.Close
{)}catch(SocketException se
if(se.ErrorCode==10060){//WSAETIMEDOUT: Connection timed out
Console.WriteLine("Aborting client, timelimit"+ TIMELIMIT+ "ms exceeded, echoed" +
;)"totalBytesEchoed+ "bytes
{} else
;)Console.WriteLine(se.ErrorCode+ ":" +se.Message
}
;)(client.Close
}
}
}
}
-8-1-27
)( Select Socket
I/O . echo
. I/O
. echo
.
. ) )( (Accept
)( Accept )( Receive
.
.
I/O.
API . )( Select Socket
I/O Select() .
I/O . Socket
I/O.
)( Select : Socket
. .
IList .
. .
Socket .
520
.( ) Socket
. Select()
. echo
Select() . Arraylist
echo . echo
. .
TcpEchoServerSelectSocket
using
using
using
using
class TcpEchoServerSelectSocket{
private const int BUFSIZE=32; //Size of receive buffer
private const int BACKLOG=5;
521
09177112161 - -
C#
I/O-9-1-27
. .NET
. I/O
callback .1 : I/O .
.2 I/O
. .3
: I/O
.
. Begin
. End
522
.
.
. NetworkStream )( Write )( Read
)( ()BeginRead ()EndWrite BeginWrite )( EndRead .
.
)( BeginRead )( BeginWrite :
public override lAsyncResult BeginRead(byte[] buffer,int offset,int size,AsyncCallback
;)callback, object state
public override lAsyncResult BeginWrite(byte[] buffer,int offset,int count ,AsyncCallback
;)callback, object state
AsyncCallback object #C
. AsyncCallback Delegate callback
. callback :
;)AsyncCallback ac = new AsyncCallback(my methodToVCall
:
{)public static void myMothodToCall(lAsyncresult result
// callback code goes here
}
callback )
( . callback :
)public static void <callbackMethodName>(lAsyncResult
IAsyncResult .
object callback .
NetworkStream
NetworkStream callback .
)( BeginRead )( BeginWrite IAsyncResult IAsyncResult .
.
AsyncWaitHandle IAsyncResult
)( WaitOne . .
callback . callback IAsyncResult
AsyncState .
.
IAsyncResult .
. :
;)public override int EndRead(IAsynResult asyncResult
;)public override void EndWrite(lAsynResult asyncResult
)( BeginRead NetworkStream
((new AsyncCallback(my callback
(callback .
523
C#
API .NET .
:
.1 : AsyncCallback callback
.
AsyncState .
.2 : callback ) ( AsyncState
IAsyncResult
callback .
.3 : IAsyncResult callback
.
5-2 NET .
5-2 .NET
Dns
BeginGetHostByName()/EndGetHostByName
()BeginResolve()/EndResolve
FileStream
()BeginRead()/EndRead
()BeginWrite()/EndWrite
NetworkStream
()BeginRead()/EndRead
()BeginWrite()/EndWrite
Socket
()BeginAccept()/EndAccept
BeginConnect()/EndConnect
()BeginReceive()/EndReceive
()BeginReceiveFrom()/EndReciveFrom
BeginSend()/EndSend
BeginSendTi()/EndSendTo
Stream
()BeginRead()/EndRead
()BeginWrite()/EndWrite
. TcpEchoClient TcpEchoServer
API .
.
)( doOtherStuff 5 .
524
Socket
TcpClient
echo
. NetworkStream
TcpEchoClientAsync
using System; //For String, IAsyncResult, ArgumentException
using System.Text; //For Encoding
using System.Net.Sockets; //For TcpClient, NetworkStream
using System.Threading; //For ManualResetEvent
class ClientState{
//Object to contain client state, including network stream
//and the send/recv buffer
private byte[] byteBuffer;
private NetworkStream netStream;
private StringBuilder echoResponse;
private int totalBytesRcvd=0; //Total bytes received so far
public ClientState(NetworkStream netStream, byte[] byteBuffer){
this.netStream=netStream;
this.byteBuffer=byteBuffer;
echoResponse=new StringBuilder();
}
public NetworkStream NetStream{
get{
return netStream;
}
}
public byte[] ByteBuffer{
set{
byteBuffer=value;
}
get{
return byteBuffer;
}
}
public void AppendResponse(String Response){
echoResponse.Append(response);
}
public String EchoResponse{
get{
return echoResponse.ToString();
}
}
public void AddToTotalBytes(int count){
totalBytesRcvd+=count;
}
public int TotalBytes{
get{
return totalBytesRcvd;
}
}
}
class TcpEchoClientAsync{
//A manual event signal we will tigger when all reads are complete:
public static ManualResetEven ReadDone=new ManualResetEvent(false);
static void Main(string[] args){
if((args.Length<2)||(args.Length>3)){//Test for cortrect # of args
throw new ArgumentException("Parameters: <server> <Word> [<Port>]");
}
String server=args[0]; // server name or IP address
525
09177112161 - -
C#
526
Tcp
TcpEchoServerAsync.cs
using System; //For Console, IAsyncResult, ArgumentException
using System.Net;
//For IPEndPoint
using System.Net.Sockets; //For Socket
using Syste.Threading
//For ManualResetEvent
class ClientState{
//Object to contain client state, including the client socket
//and the receive buffer
private const int BUFSIZE=32; //size of receive buffer
private byte[] rcvBuffer;
private Socket clntSock;
public ClientState(Socket clntSock){
this.clntSock=clntSock;
rcvBuffer=new byte[BUFSIZE]; //Receive buffer
}
public byte[] RcvBuffer{
get{
return rcvBuffer;
}
}
public Socket ClntSock{
get{
return clntSock;
}
}
}
class TcpEchoServerAsync{
private const int BACKLOG=5; //outstanding connection queue max size
static void Main(string[] args){
if(args.Length!=1) //Test for correct number of args
throw new ArgumentException("Parameters: <Port>");
int servPort=Int32.Parse(args[0]);
//Create a socket to accept client connections
Socket servSock=new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
servSock.Bine(new IPEndPOint(IPAddress.Any,servPort));
servSock.Listen(BACKLOG);
for(;;){ //Run server, accepting and servicing connections
Console.WriteLine("Thread{0}({1})-Main():calling BeginAccept",
Thread.CurrentThread.GetHashCode(),Thread.CurrentThread.ThreadState);
Console.WriteLine("Thread{0}({1})-doOtherStuff():{2}...",
Thread.CurrentThread.GetHashCode(),Thread.CurrentThread.ThreadState,x);
Thread.Sleep(1000);
}
}
public static void AcceptCallback(AsyncResult asyncResult){
Socket servSock=(Socket) asyncResult.AsyncState;
Socket clntSock=null;
try{
clntSock=servSock.EndAccept(asyncResult);
527
09177112161 - -
C#
528
:
1
MQ
MQ
-1-28
System.Messaging MQ
. 3
.
.
.
.
) (System.IO ,System.Net .
.
.
. .
.
. .
. .
Message queuing
Course order
Disconnected
C#
- 09177112161 -
. .
. .
.
.
:
.
.
. 1-28
.
.
1-28
-1-1-28
) : ( .
.
.
. .
2-28
Pocket Windows
.
. ) .(3-28
.
530
. :
.
. :
.
3-28
-2-1-28
. :
.
.
. .
.
. .
ACL . ACL
.
.
MQ3,0 .
-3-1-28
MQ3,0 WinXP Win2003 Server . Win2000 MQ2,0 HTTP
. MQ3,0 . WinXP Add-
531
C#
- 09177112161 -
4-28
-2-28 MQ
MQ .
.
-1-2-28
.
. . NET.
.
.
:
: .
: .
.
: .
532
: MQ . .
.
. .
: .
.
.
.
.
.
-2-2-28
> \msmq\storage32windir>\system .
:
Active Directory . Active
Directory .
. .
.
WorkGroup Active Directory .
Active Directory .
. WorkGroup .
) :(journal .
.
: .
.
.
. .
.
.
.
. .
.
} {CEq6AFD0020-108CFP11CCEq- 33F8EE55 .
533
C#
- 09177112161 -
.
.
.
-3-2-28
.
.
. MQ .
MMC Computer Management . WinXP MMC
Control Panel Administrative Tools Run compmgmt.msc .
Message Queuing Services and Application .
Private Queues Public Queues Action ) 5-28
( . Message Queuing Active Directory
.
5-28
Computer Management Action
) .(6-28
534
6-28
:
.
}{ .
. ) (uuid
GUID.
: uuidgen.exe guidgen.exe .
uuidgen.exe guidgen.exe .
2,0MQ .
GB2 3,0MQ .
Authenticated .
privacy level . None,Optional
Body None . Body .
Optional .
Journal .
.
. .
3,0MQ Multicast IP .
IP .
.
-3-28
.
.
.
535
C#
- 09177112161 -
-1-3-28
Computer Management . ()Create
MessageQueue . ()Create .
. MyNewPublicQueue .
$private . private$\MyNewPrivateQueue\
()Create . Label
DemoQueue . .
UUID .
;using System
;using System.Messaging
namespace Wrox.ProCSharp.Messaging
{
class Program
{
)static void Main(string[] args
{
))"using (MessageQueue queue = MessageQueue.Create(@".\MyNewPublicQueue
{
;"queue.Label = "Demo Queue
;)"Console.WriteLine("Queue created:
;)Console.WriteLine("Path: {}", queue.Path
;)Console.WriteLine("FormatName: {}", queue.FormatName
}
}
}
}
-2-3-28 CourseOrder
.
:
)) CourseOrder .
) CourseOrderSender)Windows Forms .
CourseOrder
.
. CourseOrder .Customer ,Course ,CoursOrder :
. Course.CS Course .
:
;using System
namespace Wrox.ProCSharp.Messaging
{
public class Course
{
)(public Course
{
}
)public Course(string title
536
{
this.title = title;
}
private string title;
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
}
}
: Custormer Custromer.cs
using System;
namespace Wrox.ProCSharp.Messaging
{
public class Customer
{
public Customer()
{
}
public Customer(string company, string contact)
{
this.company = company;
this.contact = contact;
}
private string company;
public string Company
{
get
{
return company;
}
set
{
company = value;
}
}
private string contact;
public string Contact
{
get
{
return contact;
}
set
{
contact = value;
}
}
}
}
: Customer CourseOrder.cs
using System;
namespace Wrox.ProCSharp.Messaging
{
public class CourseOrder
537
C#
09177112161 -{
)(public CourseOrder
{
}
;private Customer customer
public Customer Customer
{
get
{
;return customer
}
set
{
;customer = value
}
}
;private Course course
public Course Course
{
get
{
;return course
}
set
{
;course = value
}
}
}
}
CourseOrderSender .
. CourseOrder System.Messaging .
7-28 . ComboBoxCourses
Web Services Advance .NET Programming ADO.NET .
7-28
Submit the Order ()OnSubmitCourseOrder .
CourseOrder TextBox ComboBox .
MessageQueue .
Computer
private void OnSubmitCourseOrder(object sender, EventArgs e)
{
CourseOrder order = new CourseOrder();
order.Course = new Course(comboBoxCourses.SelectedItem.ToString());
order.Customer = new Customer(textCompany.Text, textContact.Text);
using (MessageQueue queue = new MessageQueue(
"FormatName:Public=")
{
queue.Send(order, "Course Order {" + order.Customer.Company + "}");
}
MessageBox.Show("Course Order submitted");
}
. Message Priority
. Message
CheckBoxPriority . Message Priority
MessagePriority . MessagePriority.High
.( 7) ( 0)
. 3 Normal
. true Recoverable
private void OnSubmitCourseOrder(object sender, EventArgs e)
{
CourseOrder order = new CourseOrder();
order.Course = new Course(comboBoxCourses.SelectedItem.ToString());
order.Customer = new Customer(textCompany.Text, textContact.Text);
using (MessageQueue queue = new MessageQueue(
"FormatName:Public="))
using (System.Messaging.Message message =
new System.Messaging.Message(order))
{
if (checkBoxPriority.Checked)
message.Priority = MessagePriority.High;
message.Recoverable = true;
queue.Send(message, "Course Order {" + order.Customer.Company + "}");
}
MessageBox.Show("Course Order submitted");
}
.(8-28 )
539
09177112161 - -
C#
8-28
. 9-28
. listOrders .
.
9-28
MessageQueue CourseOrderRecieveForm
XMLMessageFormater .
. Formater
. PeekMessage .
.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Messaging;
using Wrox.ProCSharp.Messaging;
namespace CourseOrderReceiver
{
public partial class CourseOrderReceiverForm : Form
{
private MessageQueue orderQueue;
public CourseOrderReceiverForm()
{
InitializeComponent();
orderQueue = new MessageQueue(
"FormatName:Public=");
System.Type[] types = new Type[];
types[] = typeof(CourseOrder);
types[] = typeof(Customer);
types[] = typeof(Course);
orderQueue.Formatter = new XmlMessageFormatter(types);
// start the thread that fills the ListBox with orders
Thread t = new Thread(new ThreadStart(PeekMessages));
t.IsBackground = true;
t.Start();
}
540
.( PeekMessage )
. while
.
. Windows Form .
.)( Invoke
private delegate void MethodInvoker(LabelIdMapping labelIdMapping);
private void PeekMessages()
{
using (MessageEnumerator messageEnum = orderQueue.GetMessageEnumerator())
{
while (messageEnum.MoveNext(TimeSpan.FromHours()))
{
Invoke(new MethodInvoker(AddListItem),
new LabelIdMapping(messageEnum.Current.Label,
messageEnum.Current.Id));
}
}
MessageBox.Show("No orders in the last hours. Exiting thread");
}
private void AddListItem(LabelIdMapping labelIdMapping)
{
listOrders.Items.Add(labelIdMapping);
}
. LabelIdMapping ListBox
. .
.
private class LabelIdMapping
{
private string label;
private string id;
public LabelIdMapping(string label, string id)
{
this.label = label;
this.id = id;
}
public override string ToString()
{
return label;
}
public string Id
{
get
{
return id;
}
}
}
OnOrderSelectionChanged SelectedIndexChanged ListBox
LabelIdMapping .
. TextBox .)( peekById
private void OnOrderSelectionChanged(object sender, EventArgs e)
{
LabelIdMapping labelId = (LabelIdMapping)listOrders.SelectedItem;
if (labelId == null)
541
09177112161 - -
C#
return;
System.Messaging.Message message = orderQueue.PeekById(labelId.Id);
CourseOrder order = message.Body as CourseOrder;
if (order != null)
{
textCourse.Text = order.Course.Title;
textCompany.Text = order.Customer.Company;
textContact.Text = order.Customer.Contact;
buttonProcessOrder.Enabled = true;
if (message.Priority > MessagePriority.Normal)
{
labelPriority.Visible = true;
}
else
{
labelPriority.Visible = false;
}
}
else
{
MessageBox.Show("The selected item is not a course order");
}
}
10-28
.
10-28
542
.
.
.
.
.
AdministrationQueue Message CourseOrderAck .
. .
. AcknowledgementType
AcknowledgementType.FullReceive .
;)Message message = new Message(order
= message.AdministrationQueue
;)"new MessageQueue(@".\CourseOrderAck
;message.AcknowledgementType = AcknowledgementTypes.FullReceive
queue.Send(message, "Course Order {" +
;)"}" order.Customer.Company +
;string id = message.Id
Correlation id .
Correlation id .
()MessageQueue.ReceiveByCorrelationId
.
. UseDeadLetterQueue Message true
.
TimeToReachQueue TimeToBeReceived .
.
.
ResponseQueue Message .
. CorrelationId
.
. . ()Send MessageQueue
RespenseQueue .
)public void ReceiveMessage(Message message
{
;)"Message responseMessage = new Message("response
;responseMessage.CorrelationId = message.Id
;)message.ReesponseQueue.Send(responseMessage
}
543
C#
- 09177112161 -
.
.
:
.
.
. .
.
.
true MessageQueue.Create .
MessageQueueTransaction
()Begin .
()Commit MessageQueueTransaction . )
( ()Abrot . Catch .
;using System
;using System.Messaging
namespace Wrox.ProCSharp.Messaging
{
class Program
{
)static void Main(string[] args
{
))"if (!MessageQueue.Exists(@".\MyTransactionalQueue
{
;)MessageQueue.Create(@".\MyTransactionalQueue", true
}
;)"MessageQueue queue = new MessageQueue(@".\MyTransactionalQueue
= MessageQueueTransaction transaction
;)(new MessageQueueTransaction
try
{
;)(transaction.Begin
;)queue.Send("a", transaction
;)queue.Send("b", transaction
;)queue.Send("c", transaction
;)(transaction.Commit
}
catch
{
;)(transaction.Abort
}
}
}
}
544
-4-28 MessageQueue
MessageQueue.Create .
. .
MessageQueueInstaller .
installuti.exe ()Install .
VS2005 MessageQueueInstaller Windows Form .
MessageQueue
Add Installer . MessageQueueInstaller
.
-5-28
Message Queuing .
.
.
MessageQueue Message . MessageQueue
Message .
545
C#
- 09177112161 -
NET Com
.
.
Com ActiveX .
NET. .NET Com .
NET. ActiveX Com 1 .NET
Com API 32Win .
-1-29 2 ActiveX
ActiveX Com
. OCX
ActiveX VB ++C . ActiveX .
ActiveX ActiveX .
. ActiveX .
ActiveX .NET 2005VS . ActiveX
. 2005VS AxImp
NET. .
Form Windows
. 6VB ActiveX Control .
. User Control
Properties . Calculator . Project Explorer Project
Properties CalcControl .
CalcControl . 1-29 :
546
Exposing
Import
COM NET.
1-29
1-29 VB . Code View 4
:
1-29
Public Function _
Add(left As Double, right As Double) _
As Double
Add = left + right
End Function
Public Function _
Subtract(left As Double, right As Double) _
As Double
Subtract = left - right
End Function
Public Function _
Multiply(left As Double, right As Double) _
As Double
Multiply = left * right
End Function
Public Function _
Divide(left As Double, right As Double) _
As Double
Divide = left / right
End Function
547
C#
- 09177112161 -
2-29
. 3-29
3-29
TestForm CalcControl .
. . .
4-29 :
4-29
.btnAdd, btnSubtract, btnMultiply, btnDivide: 2-29
.
.
2-29
)(Private Sub btnAdd_Click
_ = Label.Caption
_ calcControl.Add(CDbl(Text.Text),
))CDbl(Text.Text
End Sub
) (Private Sub btnDivide_Click
_ = Label.Caption
_ calcControl.Divide(CDbl(Text.Text),
))CDbl(Text.Text
End Sub
) (Private Sub btnMultiply_Click
_ = Label.Caption
548
NET. COM
_ calcControl.Multiply(CDbl(Text.Text),
))CDbl(Text.Text
End Sub
) (Private Sub btnSubtract_Click
_ = Label.Caption
_ calcControl.Subtract(CDbl(Text.Text),
))CDbl(Text.Text
End Sub
-2-29 NET.
CalcControl . 6VB
. CalcControl.ocx NET. .
CalcControl.ocx 132Regsvr . CalcControl
.NET :
CalcControl.ocx
regsvr32
5-29
-1-2-29
ActiveX 2005VS : 2005VS
aximp NET SDK. . 2005VS
Tools
Items
ToolBox
Choose
Components
Com
CalcControl.Calculator . 6-29 .
C:\WINDOWS\system32
549
C#
- 09177112161 -
6-29
CalcControl NET. 2005VS Choose ToolBox Tools
. 2005VS .
.
-2-2-29
aximp.exe .
7-29.
7-29
aximp.exe ActiveX :
: AxCalcControl.dll NET.
: CalcControl.dll .NET
: AxCalcControl.pdb
550
COM NET.
8-29
-3-2-29
. 9-29
.
9-29
. 6VB
3-29 .
.
3-29
private void btnAdd_Click(object sender, System.EventArgs e)
{
double left = double.Parse(textBox.Text);
double right = double.Parse(textBox.Text);
label.Text = axCalculator.Add( ref left, ref right).ToString( );
}
private void btnDivide_Click(object sender, System.EventArgs e)
{
double left = double.Parse(textBox.Text);
double right = double.Parse(textBox.Text);
label.Text = axCalculator.Divide(ref left, ref right).ToString( );
}
private void btnMultiply_Click(object sender, System.EventArgs e)
{
double left = double.Parse(textBox.Text);
double right = double.Parse(textBox.Text);
label.Text = axCalculator.Multiply(ref left, ref right).ToString( );
}
551
09177112161 - -
C#
Double.Parse 1
. 2
. 10-29 . 3
10-29
Com -3-29
Com . ActiveX
. COM DLL ActiveX
. COM 6VB NET.
. 6VB COM DLL . ActiveX DLL
4-29 . . ComCalculater ComCalc
.
22-4
Public Function _
Add(left As Double, right As Double) _
As Double
Add = left + right
End Function
Public Function _
Subtract(left As Double, right As Double) _
As Double
Subtract = left - right
End Function
Public Function _
Multiply(left As Double, right As Double) _
As Double
Multiply = left * right
End Function
Public Function _
Divide(left As Double, right As Double) _
As Double
1
Textbox
Double
Label
552
COM NET.
DLL . Calculator
. 11-29 . ComCalculator Refrences
11-29
ComTestForm -1-3-29
Comcalc . Com
. 5-29 .
5-29
Private Sub btnAdd_Click()
Dim theCalc As New ComCalc
Label.Caption = _
theCalc.Add(CDbl(Text.Text), _
CDbl(Text.Text))
End Sub
Private Sub btnDivide_Click( )
Dim theCalc As New ComCalc
Label.Caption = _
theCalc.Divide(CDbl(Text.Text), _
CDbl(Text.Text))
End Sub
Private Sub btnMultiply_Click( )
Dim theCalc As New ComCalc
Label.Caption = _
theCalc.Multiply(CDbl(Text.Text), _
CDbl(Text.Text))
End Sub
Private Sub btnSubtract_Click( )
Dim theCalc As New ComCalc
Label.Caption = _
theCalc.Subtract(CDbl(Text.Text), _
CDbl(Text.Text))
End Sub
553
C#
- 09177112161 -
-3-3-29
Com Dll VB6 . Com NET
. Com . .
IDE .
Tlbimp.exe Tlbimp.exe . interop
. NET Com Rcw1 . Rcw NET
Com .
-4-3-29
Comcalculator.Dll NET 32Regsvr .
Com NFT Tlbimp.exe . :
] out/:
Tlbimp.exe
dll
12-29 .
12-29
-5-3-22
Com ComDllTest .
IDE .
Add
554
COM NET.
13-29
RCW Tlbimp
C:\Documents and Settings\Administrator\Application
Data\Microsoft\VisualStudio\RCW.
.
Tlbimp.exe ComDll Dll
ComcalculaorDllNETDll . Projects
(14-29 ) . .
14-29
. 6-29
6-29
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
#endregion
namespace ComDLLTest
{
partial class Form : Form
{
public Form( )
{
InitializeComponent( );
}
private void btnAdd_Click(
object sender, System.EventArgs e )
{
Double left, right, result;
left = Double.Parse( textBox.Text );
right = Double.Parse( textBox.Text );
ComCalculatorDLLNET.ComCalc theCalc =
new ComCalculatorDLLNET.ComCalc( );
555
09177112161 - -
C#
. Comcalculater.Comcalc Activex
. . NET Com
. 15-29
15-29
-6-3-29
. Com
. 6-29
Comcalculater.ComCalc .
.
. Comcalc Type
556
COM NET.
Type comCalcType;
comCalcType = Type.GetTypeFromProgID("ComCalculator.ComCalc");
. NET
. Comcalc CreateInstance
object comCalcObject = Activator.CreateInstance(comCalcType);
. InvokeMember
CreateInstance
. InvokeMember
object[] inputArguments = {left, right };
result = (Double) comCalcType.InvokeMember(
"Subtract", // the method to invoke
BindingFlags.InvokeMethod, // how to bind
null, // binder
comCalcObject, // the COM object
inputArguments); // the method arguments
. Result Double
. 16-29 .
16-29
.
System.Reflection using 7-29 . Inroke
.
7-29
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
#endregion
namespace LateBinding
{
partial class Form : Form
{
public Form( )
{
InitializeComponent( );
}
private void btnAdd_Click(
object sender, System.EventArgs e )
{
Invoke( "Add" );
}
557
09177112161 - -
C#
NET -4-29
Regasm . Com NET
.
: . GAC Dll . Dll Regasm
Regasm MyAssembly.dll
4 C#Dll .
. 8-29 .
8-29
using System;
using System.Reflection;
[assembly: AssemblyKeyFile("test.key")]
namespace Programming_CSharp
{
558
COM NET.
public
{
public
{
}
public
{
return
}
public
{
return
}
public
{
return
}
public
{
return
}
}
}
class Calculator
Calculator( )
Double Add (Double left, Double right)
left + right;
Double Subtract (Double left, Double right)
left - right;
Double Multiply (Double left, Double right)
left * right;
Double Divide (Double left, Double right)
left / right;
. ProgrammingCsharpDll Calculater.CS
-29 . Signing Strong
. 17
17-29
. 18-29 Create Key
22-8
559
C#
- 09177112161 -
GAC .
gacutil /i ProgrammingCSharpDLL.dll
Regasm ProgrammingCSharpDLL.dll
VBScript Com .
9-29 .
9-29
dim calc
dim msg
dim result
)"set calc = CreateObject("Programming_CSharp.Calculator
)result = calc.Multiply(
"msg = " * =" & result & ".
)Call MsgBox(msg
) 19-29 (.
19-29
-1-4-22
NET Dll .
TlbExp .
TlbExp ProgrammingCSharpDLL.dll /out:Calc.tlb
560
NET. COM
20-29
Com .
P/Invoke-5-29
#C . FCL
. 2,0 NET P/Invoke .
NET Platform P/Invoke API .
DLL .
MoveTo FileInfo .
;)"file.MoveTo(fullName + ".bak
.dll32Kernel MoveFile .
Static Extern DllImport .
[DllImport("kernel.dll", EntryPoint="MoveFile",
ExactSpelling=false, CharSet=CharSet.Unicode,
])SetLastError=true
(static extern bool MoveFile
;)string sourceFile, string destinationFile
DllImport P/Inroke
. .
:DllName Dll .
:EntryPoint Dll .
: ExactSpelling CLR CLR .
:Charset .
:SetLastError true Marshal.GetLastWin32Error
.
MoveFile .
;)"Tester.MoveFile(file.FullName,file.FullName + ".bak
561
09177112161 - -
10-29
#region Using directives
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
#endregion
namespace UsingPInvoke
{
class Tester
{
// declare the WinAPI method you wish to P/Invoke
[DllImport( "kernel.dll", EntryPoint = "MoveFile",
ExactSpelling = false, CharSet = CharSet.Unicode,
SetLastError = true )]
static extern bool MoveFile(
string sourceFile, string destinationFile );
public static void Main( )
{
// make an instance and run it
Tester t = new Tester( );
string theDirectory = @"c:\test\media";
DirectoryInfo dir =
new DirectoryInfo( theDirectory );
t.ExploreDirectory( dir );
}
// Set it running with a directory name
private void ExploreDirectory( DirectoryInfo dir )
{
// make a new subdirectory
string newDirectory = "newTest";
DirectoryInfo newSubDir =
dir.CreateSubdirectory( newDirectory );
// get all the files in the directory and
// copy them to the new directory
FileInfo[] filesInDir = dir.GetFiles( );
foreach ( FileInfo file in filesInDir )
{
string fullName = newSubDir.FullName +
"\\" + file.Name;
file.CopyTo( fullName );
Console.WriteLine( "{} copied to newTest",
file.FullName );
}
// get a collection of the files copied in
filesInDir = newSubDir.GetFiles( );
// delete some and rename others
int counter = ;
foreach ( FileInfo file in filesInDir )
{
string fullName = file.FullName;
if ( counter++ % == )
{
// P/Invoke the Win API
Tester.MoveFile( fullName, fullName + ".bak" );
Console.WriteLine( "{} renamed to {}",
fullName, file.FullName );
}
else
{
file.Delete( );
Console.WriteLine( "{} deleted.",
562
C#
COM NET.
fullName );
}
}
// delete the subdirectory
newSubDir.Delete( true );
}
}
}
Output (excerpt):
c:\test\media\newTest\recycle.wav renamed to
c:\test\media\newTest\recycle.wav
c:\test\media\newTest\ringin.wav renamed to
c:\test\media\newTest\ringin.wav
563
DLL
NET. . DLL
EXE . DLL
.
NET. .
.
GIF.
.
-1-30 PE
. PE . PE
NET. PE . PE DLL EXE .
. .
. .
.
.
-1-1-30
. - 1
.
Portable Executable
-2-1-30
.
.
. IDE
. . internal
.
-3-1-30 2
. :
) (
public .
. ILDASM .
ILDASM 1-30 .
1-30
) ( . Manifest 2-30
.
565
self describing
manifest
C#
- 09177112161 -
2-30
. mscorlib
. mscorlib NET.
NET Platform. .
. .
.
-2-30
. 2005VS .
EXE DLL .
. .
.
.
. .
) EXE ( DLL .
.
.
-1-2-30
. Fraction .
. 1-30 .
1-30
#region Using directives
566
-
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace ProgCS
{
public class Fraction
{
private int numerator;
private int denominator;
public Fraction( int numerator, int denominator )
{
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction Add( Fraction rhs )
{
if ( rhs.denominator != this.denominator )
{
return new Fraction(
rhs.denominator * numerator +
rhs.numerator * denominator,
denominator * rhs.denominator);
}
return new Fraction(
this.numerator + rhs.numerator,
this.denominator );
}
public override string ToString( )
{
return numerator + "/" + denominator;
}
}
}
. ProgCS.Fraction . ProgCS Fraction
. ProgCS
567
C#
- 09177112161 -
. AssemblyInfo.CS
. AssemblyInfo.CS . VS
.
VS . addModule/
. makefile .
NotePad . MAKEFILE .
makefile .
3-30 makefile . makefile
Fraction.CS Calc.CS AssemblyInfo.CS . NET.
CD . nmake .
MySharedAssembly.DLL \ Bin .
3-30
ASSEMBLY= MySharedAssembly.dll
BIN=.\bin
SRC=.
DEST=.\bin
CSC=csc /nologo /debug+ /d:DEBUG /d:TRACE
MODULETARGET=/t:module
LIBTARGET=/t:library
EXETARGET=/t:exe
REFERENCES=System.dll
MODULES=$(DEST)\Fraction.dll $(DEST)\Calc.dll
METADATA=$(SRC)\AssemblyInfo.cs
all: $(DEST)\MySharedAssembly.dll
# Assembly metadata placed in same module as manifest
)$(DEST)\$(ASSEMBLY): $(METADATA) $(MODULES) $(DEST
$(CSC) $(LIBTARGET) /addmodule:$(MODULES: =;) /out:$@ %s
# Add Calc.dll module to this dependency list
)$(DEST)\Calc.dll: Calc.cs $(DEST
$(CSC) $(MODULETARGET) /r:$(REFERENCES: =;) /out:$@ %s
# Add Fraction
)$(DEST)\Fraction.dll: Fraction.cs $(DEST
$(CSC) $(MODULETARGET) /r:$(REFERENCES: =;) /out:$@ %s
$(DEST)::
))!if !EXISTS($(DEST
)mkdir $(DEST
!endif
makefile .
ASSEMBLY= MySharedAssembly.dll
. BIN
.
SRC=.
DEST=.\bin
.
)$(DEST)\$(ASSEMBLY): $(METADATA) $(MODULES) $(DEST
$(CSC) $(LIBTARGET) /addmodule:$(MODULES: =;) /out:$@ %s
bin . nmake
. .
.
METADATA=$(SRC)\AssemblyInfo.cs
568
DLL .
MODULES=$(DEST)\Fraction.dll $(DEST)\Calc.dll
.
MySharedAssembly.DLL .
)$(DEST)\$(ASSEMBLY): $(METADATA) $(MODULES) $(DEST
$(CSC) $(LIBTARGET) /addmodule:$(MODULES: =;) /out:$@ %s
nmake . Calc.DLL nmake .
)$(MODULETARGET
)$(CSC
)$(DEST
(REFRENCES:=;) 4DEST)\CALC.DLL:CALC.CS
/OUT:$@%S
Fraction.DLL .
)$
)$(MODULETARGET
)$(CSC
)$(DEST
DEST)\FRACTION.DLL:FRACTION.CS
(REFRENCES:=;) /OUT:$@%S4/R:
3-17
) 4-30
(.
4-30
569
09177112161 - -
C#
ProgCS.Calc ( mscorlib)
. ProgCS.Fraction
Calc.DLL MySharedAssembly.DLL : DLL
. Fraction.DLL
-2-2-30
. 4-30 .
. Test.CS
4-30
namespace Programming_CSharp
{
using System;
public class Test
{
// main will not load the shared assembly
static void Main( )
{
Test t = new Test( );
t.UseCS( );
t.UseFraction( );
}
// calling this loads the myCalc assembly
// and the mySharedAssembly assembly as well
public void UseCS( )
{
ProgCS.myCalc calc = new ProgCS.myCalc( );
Console.WriteLine("3+5 = {0}\n3*5 = {1}",
calc.Add(3,5), calc.Mult(3,5));
}
// calling this adds the Fraction assembly
public void UseFraction( )
{
ProgCS.Fraction frac1 = new ProgCS.Fraction(3,5);
ProgCS.Fraction frac2 = new ProgCS.Fraction(1,5);
ProgCS.Fraction frac3 = frac1.Add(frac2);
Console.WriteLine("{0} + {1} = {2}",
frac1, frac2, frac3);
}
}
}
570
:
3+5 = 8
3*5 = 15
3/5 + 1/5 = 4/5
()Main .
()Main . Calc Fraction ()Main .
UseFraction UseCalc .
AssemblyResolver AssemblyResolver .
NET. . .
.
DLL 4-30 bin . 17-5
()Main .
5-30
. ) 6-30 (.
6-30
571
C#
- 09177112161 -
UseFraction DLL .
-3-2-30
: .
. .
. #C
. ) ( .
.
. .
.
DLL
.
.
-4-2-30
.
.
:
572
: . .
.
.
:
.
: GAC . CLR
.
-5-2-30 DLL
DLL . . A
DLL Windows . B
. A ) A B ( .
B DLL A A .
DLL . DLL
DLL . Pat Johnson
. DLL
DLL DLL
.
. .
-3-30
NET. GAC .
.
.
4) 1:0:2204:21 : ( . )(1:0
. ) (2204 ) (21 .
.
.
. AssemblyResolver CLR
.
-1-3-30
:
573
C#
- 09177112161 -
.
.
.
. .
- .
) (Hash . Hash
) Hash ( .
. CLR . Hash
.
.
sn .
sn -k c:\myStrongName.snk
k .
.
.
.
;using System.Runtime.CompilerServices
])"[assembly: AssemblyKeyFile("c:\myStrongName.key
GAC-2-3-30
GAC
. gacutil GAC .
gacutil /i MySharedAssembly.dll
Explorer
SystemRoot%\assembly% .
-3-3-30
. ) 1-30 4-30
( Calc.CS Fraction.CS.
: bin
MySharedAssembly.DLL .
) (MySharedAssembly CopyLocal false . .
.
Unhandled Exception: System.IO.FileNotFoundException: File or assembly name
MySharedAssembly, or one of its dependencies, was not found.
"File name: "MySharedAssembly
) (at Programming_CSharp.Test.UseCS
) (at Programming_CSharp.Test.Main
574
DLL . .
MySharedAssembly . :
GAC .
:1
.
sn -k keyFile.snk
AssemblyInfo.CS MySharedAssembly.DLL .
])""([assembly: AssemblyKeyFile
.
])"[assembly: AssemblyKeyFile("keyFile.snk
. DLL ILDASM
. ) 8-30(.
8-30
. GAC
DLL . DLL
.
sn -T MySharedAssembly.dll
SN . :
Public key token is 01fad8e0f0941a4d
: . GAC
GAC . Explorer
%SystemRoot% Assembly GAC Explorer
.
GAC .
Gacutil /i mySharedAssembly.dll
sn 9-30
.
9-30
575
C#
- 09177112161 -
. .
) 10-30
(.
10-30
MySharedAssembly
GAC .
ILDASM . DLL .
.
-4-3-30
.
) ( .
.
. ) / / ( ) / / ( .
576
1
2005#C
VS #VC #VC .
. #C
:
-
2005VS . #J VB
++VC VS . Tools For Office Professional Standard
VS Team
System .
.
-
:Express #VC
VS.
1
#C . .
VS .
2005#VC Team System
-1 CD 2005VS . CD
setup.exe . 1.
-2 . VS
.
-1 VS
VS . VS .
Install Visual Studio .
-3 Continue .
-4 VS :
-
:Default VS .
:Full VS .
VS .
:Custom VS
.
VS Custom
Next .
-5 VS .
. 2005VC++
. .
SQL Server
Express 2005 .
:
-
Feature Description .
VS 2005#VC .
. . MB100
.
2
579
C#
- 09177112161 -
-6 Install .
. .
-7 .
.
. Done VS.
2005#VC
#C 2005#VC .
NotePad . #VC NotePad
. VS IDE .
IDE VS
.
3
Profile Setup
IDE 2005VS .
. Start
All Programs 2005Microsoft Visual Studio Microsoft Visual Studio
2005 . VS
Choose Default
-1 VS
. IDE .
IDE .
Word Excel.
2005VS
. IDE VS
Community , Window, Test , Tools , Data , View ,Edit , File Help .
VS 4 .
4
. .
:
: File .
. File
.
: Edit :
:Project
.
: Build
#VC ) Start Word ( Excel
: Debug VS .
Debugger VS2005 . Debugger
.
: Data .
) VS
) (Design ( .
: Format .
) TextBox (...
.
: Test Test
.
: Window
Word Excel .
581
C#
- 09177112161 -
IDE . VS
.
:Community
.
IDE VS Image Editor Formatting .Text Editor
Toolbars View .
.
. ..File New Project
) (5 .
5
.
. .
File Project .
) Copy Cut .(Paste
....
). ( .
.
VS Solution Explorer
Start Page Object Browser Toolbox Properties .
.
: .
.
582