1
004.43
26
26 Microsoft Visual C#. . 8- . .: , 2017.
848.: . ( ).
ISBN 978-5-496-02372-6
, C#
Visual Studio 2015. , ,
, ,
, , LINQ, ,
- .
, Visual C# ,
, . Microsoft .NET
Visual Studio .
32.973.2-018.1
004.43
Microsoft Press. .
.
, , , -
. , ,
, .
...................................................................................................17
1. C#............................................................................................ 32
2. , .................................. 65
3. .................................. 93
4. ........................................... 125
5. ....... 147
6. ....................................................................... 168
7. ........................................... 196
8. .................................................... 222
9.
....................................................................................... 250
21. , ,
........................................................................................................ 546
IV.
Windows C#............................................ 597
24.
........................................................................................ 649
25.
Windows.............................................................. 698
26.
Windows............................................................................................. 755
27.
Windows............................................................................................. 789
...................................................................................................17
..........................................................................................18
...........................................................................................18
............................................................................................................................19
.............................................................................19
.........................................................21
..................................................................................................................21
.................................................................................................................................22
...................................................................................................22
.........................................................................................23
.............................................................................................................................28
...........................................................................................29
...................................................................................................30
I. Microsoft Visual C#
Microsoft Visual Studio 2015.................................................. 31
1. C#..................................................................32
VisualStudio2015....................................................32
Visual Studio 2015.......................................33
....................................................................................38
Microsoft IntelliSense......................................38
..................................................................41
...........................................................................................45
............................................................46
.....................................................................................48
Visual Studio 2015.....................................49
....................................................................51
UWP-............................................................................................57
.........................................................61
.............................................................................................................................................64
....................................................................................................................64
2. , .......................65
............................................................................................................65
8
...........................................................................................66
..............................................................................................67
......................................................................................................68
...................................................................68
....................................................................................................69
.................................................................................70
........................................71
, .........................71
.....................................................................77
.................................................................................................................78
................................................................80
.................................................85
............................86
................................................................87
.............................88
...............................................................................89
....................................90
.............................................................................................................................................91
....................................................................................................................91
3. .......................93
..........................................................................................................................94
...............................................................................................................94
.......................................................................................95
-.................................................................................96
........................................................................................................................98
.......................................................................98
..................................................................101
............................................................101
.....................................................102
............................................................................................................103
........................................................................................................................104
............................................................................................................109
.............114
.................................................................115
..............................................................................116
,
.............................................................117
...........................................................................................................................................123
..................................................................................................................123
4. ............................... 125
........................................................................................126
....................................................................................126
................................126
....................................127
..........................................................................................................128
9
......129
if ..................................................130
if......................................................131
........................132
if-..............................................................................133
switch.......................................................................................139
switch............................................140
switch.......................................141
...........................................................................................................................................145
..................................................................................................................145
5. .... 147
..................................................148
while.........................................................................................................149
for.......................................................................................................154
for.................................156
do.......................................................................................................157
...........................................................................................................................................166
..................................................................................................................167
6. .................................................. 168
.....................................................................................................................169
.......................................................169
.........................................................................................171
.......................................173
.............................................................................173
........................................................................................179
......181
checked.............................................................................................182
...................................................................................183
...................................................................................................................186
finally....................................................................................................191
...........................................................................................................................................193
..................................................................................................................194
7. ............................. 196
.................................................................................197
....................................................................................................................197
.................................................................................198
.......................................................................................................199
..................................................................................................201
...............................................................................................202
....................................................212
.................................................................213
10
const.........214
................................................................214
.............................................215
...........................................................................................................218
...........................................................................................................................................220
..................................................................................................................220
8. .................................... 222
....................................................222
,
..............................................................................................................................229
, .........................................231
, ........232
ref out....................................................................................233
ref-..................................................................................................234
out-.................................................................................................235
................................................................................237
............................................................................................239
System.Object...................................................................................................................240
.........................................................................................................................................241
.....................................................................................................................................242
................................................................................244
is.............................................................................................................................245
as............................................................................................................................245
...........................................................................................................................................247
..................................................................................................................248
9.
.............................................................. 250
.........................................................................................................250
...............................................................................................251
.........................................................................................251
...........................................................252
..........................................................................253
..............................................................................................................256
.....................................................................................................257
, ....................259
............................................................................260
..........................................................261
.....................................................................266
...........................................................................................................................................270
..................................................................................................................271
10. ............................................................ 272
............................................................................................272
...............................................................................273
........................................................................................273
11
.................................................................................274
.......................................276
............................................................277
...........................................................277
...................................................................................................................279
..............................................................................................................281
..............................................................................282
...................................................................................283
...........................................................................................................................................295
..................................................................................................................295
11. .................................. 297
, ...........................................................................297
.....................................................................298
...........................................................................................300
params object[ ]...........................................................302
params-.....................................................................................304
.........................307
...........................................................................................................................................309
..................................................................................................................310
12. .............................................................. 311
?..........................................................................................................311
.................................................................................................312
System.Object.........................................................314
.........................................................................315
.......................................................................................................316
.............................................................................................318
...............................................................................319
override.................................321
..............................................................323
.......................................................................330
...........................................................................................................................................335
..................................................................................................................335
13. .......... 337
....................................................................................338
.................................................................................................339
....................................................................................................339
..........................................................................341
..........................................................................342
.......................................................................................342
, .........................................................345
.............................................................345
...................................................................................................................355
..........................................................................................................357
12
.................................................................................................................357
........................................................................................................358
.................................................358
...........................................................................................................................................365
..................................................................................................................366
14. ............ 367
..................................................................................................368
.....................................................................................................369
?.........................................................................371
?......................................................................................372
.......................................................................................................................373
..............................................................................................................374
.................................................................................374
...........................375
using IDisposable .............................................................376
Dispose ..........................................................................378
...........380
...........................................................................................................................................389
..................................................................................................................389
...........................................................................................................................................433
..................................................................................................................434
..........................................................590
, .......591
....................................592
.....................................................................593
...........................................................................................................................................596
..................................................................................................................596
IV.
Windows C#............................................ 597
.........................................................................................................................................684
...........................................................................................................................................695
..................................................................................................................695
25.
Windows............................................ 698
Windows..................................................................................................................700
Windows.........................................................703
.........................706
Grid...................................................................................................................723
.......................................................................................................733
.........................................742
...........................................................................................................................................753
..................................................................................................................754
26.
Windows.................................................................. 755
Model-View-ViewModel.................................................................756
..........................757
...............................763
ComboBox....................................................................................................................769
(ViewModel)........................................................771
...........................................................776
...........................................................................................................................................787
..................................................................................................................787
27.
Windows.................................................................. 789
....................................................................................790
Azure SQL Database
AdventureWorks...................................................................................................................792
entity-....................................................................................................797
- REST..........................................................807
, REST -.............................824
.....835
...........................................................................................................................................844
..................................................................................................................845
Microsoft Visual C#
, , -
Microsoft .NET Framework. Visual C#
C++ Microsoft Visual Basic,
, .
C# 1.0 2001. C# 2.0 Visual
Studio 2005 ,
, . C# 3.0,
Visual Studio 2008, , --
, , ,
, Language-Integrated Query (LINQ). -
C#4.0 2010 ,
.
, , , -
, .
.NET Framework,
C# 4.0, ,
(Task Parallel Library (TPL)). TPL
, -
, -
. C# 5.0
, async await.
C# 6.0 , ,
.
, ( String.
Format !),
, , ,
. .
Microsoft Windows
10. Windows -
18
,
,
, . -
Windows 10
Windows (Universal Windows Platform (UWP)),
Windows 10, ,
, , ,
(Internet of Things
(IoT)). C#
,
.
,
,
,
.
, Visual Studio 2015,
,
, -
, .
, ,
!
, ,
C# Visual Studio 2015
.NET Framework 4.6. , -
C#
,
Windows 10.
, C#,
. -
C#.
,
,
19
.
I Microsoft Visual C# Microsoft Visual Studio 2015 -
C#
Visual Studio.
II C# -
C# ,
, .
III C# -
, C# ,
.
IV Windows
C# -
Windows 10 C#
, .
. ,
, C# ,
C, C++, Java Visual Basic. ,
, .
1. -
--
- .
2.
.
3. IV
20
- 1. -
-
, C, .
- 2. ,
C# C# Visual Studio 2015, -
6- 22-.
3. IV
- 1. -
--
- .
, C++ 2. ,
Java C# Visual Studio 2015, -
8- 22-.
3.
Windows IV
1. -
Visual Basic C#
.
2.
.
3.
Windows IV .
4. ,
-
C# Visual Studio 2015
1. -
.
2.
,
, -
.
,
.
21
,
.
, -
, ,
.
.
, ( ),
.
(+) ,
. , Alt+Tab , ,
Alt, Tab.
, ,
:
Windows 10 ( );
, 1,6 (-
2);
1 ( 32- ) 2 ( 64- )
( 512
);
10 ;
5400 ./;
22
, DirectX 9
1024 768;
DVD- ( Visual Studio DVD-);
-
.
Windows -
Visual Studio 2015 .
UWP-
. -
https://msdn.microsoft.com/library/windows/apps/dn706236.aspx.
,
.
, , - http://aka.
ms/sharp8e/companioncontent.
Visual Studio 2015.
Windows Visual Studio.
, -
, ,
.
1. CSharpSBS.zip, - ,
.
2. ,
. , Accept (),
Next ().
, -
-,
CSharpSBS.zip.
23
,
. , -
, .
NuGet,
. .
, ,
Visual Studio , -
, . -
, .
Visual Studio 2015, , .
,
.
Complete.
Chapter 1
TextHello .
, -
Hello ,
,
Chapter 2
PrimitiveDataTypes ,
,
-
MathsOperators
(+, , *, /, %)
Chapter 3
Methods
MathsOperators
DailyRate -
, -
Visual Studio 2015
24
DailyRate Using , ,
Optional Parameters , -
Chapter 4
Selection , -
, ,
if
SwitchStatement switch
XML-
Chapter 5
WhileStatement while, -
-
DoStatement
Chapter 6
MathsOperators MathsOperators
2 ,
-
. -
try catch,
Chapter 7
Classes -
, -
, . ,
new
Chapter 8
Parameters -
. -
ref out
Chapter 9
StructsAndEnums struct
,
25
Chapter 10
Cards -
Chapter 11
ParamsArray -
params ,
int-
Chapter 12
Vehicles -
.
ExtensionMethod ,
int-, , -
10 -
Chapter 13
Drawing
. ,
,
Drawing Using
Interfaces Drawing -
, ,
Chapter 14
GarbageCollectionDemo -
-
Dispose
Chapter 15
AutomaticProperties -
26
Chapter 16
Indexers :
, , -
,
Chapter 17
BinaryTree ,
,
IteratorBinaryTree -
- Tree
Chapter 18
Cards 10, -
Chapter 19
BinaryTree -
IEnumerator<T>
- Tree
IteratorBinaryTree -
- Tree
Chapter 20
Delegates , -
, .
, , -
, ,
Chapter 21
QueryBinaryTree LINQ-
-
Chapter 22
ComplexNumbers , -
-
27
Chapter 23
GraphDemo
, UWP-.
GraphDemo With
Cancellation
ParallelLoop , , -
Parallel
Chapter 24
PLINQ
PLINQ
CalculatePI
.
Chapter 25
Customers
,
-. XAML-
,
Chapter 26
DataBinding Customers,
, -
.
INotifyPropertyChanged, -
28
ViewModel Customers
, ,
Model View ViewModel (-
)
Chapter 27
Web Service -,
- ASP.NET Web API, -
Customers
SQL Server. -
entity-, Entity
Framework
, , comp@piter.com
( , ).
!
- www.piter.com
.
, Win
dows 10 ,
26. Windows 10
.
, ,
, .
,
.
(Devon Musgrave) Microsoft
Press, . (
Microsoft Patterns & Practices,
.) , , ,
Windows 10 Visual Studio 2015, ,
,
!
(Jason Lee), -
, Content Master ( , ,
, ,
). -
. ,
, , ,
, ,
.
(Marc Young) , -
-
. .
, , ,
,
.
,
.
30
, , , -
, (,
).
, -
, .
, ,
(
, ).
CM Group Ltd, ,
. .
30- . -
CP/M, -
C/Oracle UNIX,
, C# JavaScript,
, , Windows 10 Microsoft Azure.
Microsoft .NET
Framework, Windows Communication Foundation 4 Step
By Step ( Microsoft Press).
I
Microsoft
Visual C# Microsoft
Visual Studio 2015
C# ,
Visual Studio 2015.
I , Visual Studio -
, ,
, -
C#. ,
Visual Studio ,
.
1 C#
, :
Microsoft Visual Studio 2015;
C#;
;
C#.
Visual Studio 2015,
, -
Microsoft Windows. Visual Studio 2015
C#,
,
. Visual Studio 2015
C#,
Windows.
VisualStudio2015
Visual Studio 2015
, , -
C#-,
Windows. ,
,
, C++, Visual Basic F#. -
Visual Studio 2015 ,
.
VisualStudio2015 33
(graphical user interface (GUI)) .
. 1.1
(File) (New),
(Project). (New Project).
34 1 C#
, ,
. -
, ,
.
(Installed),
(Templates) Visual C#.
.NET Framework 4.6 (Console
Application) (.1.2).
. 1.2
(Location) C:\Users\YourName\Documents\
Microsoft Press\VCSBS\Chapter1. YourName
, Windows.
,
C:\Users\YourName\Documents
Documents.
. 1.3
. 1.4
36 1 C#
-
, .
, ,
Windows. .
.
, , -
.
,
, .
,
.
(Solution Explorer),
(.1.5).
. 1.5
, -
.
, -
.
VisualStudio2015 37
-
, Visual Studio 2015
.
TestHello. .
.
, Visual Studio 2015 ,
. -
Documents\Microsoft Press\VCSBS\Chapter 1\TestHello, ,
TestHello.sln.
TestHello. C#.
, , -
, .
. TestHello.csproj
\Microsoft Press\VCSBS\Chapter 1\TestHello\TestHello
.
Properties. TestHello. (
Properties), , AssemblyInfo.cs.
, -
, , ..
. .
(References). -
, .
C# . Microsoft
.NET Framework . -
,
,
. (Referenses), -
, Visual Studio 2015 .
.NET Framework Microsoft Visual
Studio2015. -
, .
App.config. . -
. ,
, ,
.NET Framework, .
.
38 1 C#
Program.cs. C#, -
.
. -
Visual Studio 2015 , .
Program.cs Program, Main. C#
,
.
7 , -
9 .
Main . -
, Program, .NET Framework
.
( 3
, 7
.)
C# . Main -
M.
, -
Hello World!, Hello World
, .
Microsoft IntelliSense
,
Program.cs, Main
( { ),
.
Console,
, ,
.
.
Console C,
IntelliSense. C#
39
, . ,
Console.
, Cons, IntelliSense
Console (.1.6),
.
. 1.6
Main :
Console .
Console .
IntelliSense, , Console.
, WriteLine .
W, r, i, t, e, L,
WriteLine, .
IntelliSense ,
WriteLine. Main :
, (. IntelliSense.
,
WriteLine, ,
, Console WriteLine,
19 .
WriteLine
. ( 3.)
Main :
static void Main(string[] args)
{
Console.WriteLine(
}
WriteLine,
.
, ), -
, ;. Main :
static void Main(string[] args)
{
Console.WriteLine();
}
"Hello World!" , ,
,
WriteLine. Main :
,
, ( ), , { },
.
, .
IntelliSense
IntelliSense
. -
.
.
41
( 3)
( 15
)
( 7)
( 9)
( 9)
( 12 )
( 13 -
)
( 17 )
( 17)
( )
IntelliSense.
, (//),
. , -
, ,
. , ,
:
Console.ReadLine(); // ,
,
. ,
(/*). , -
(*/),
. -
.
(Build) (Build Solution).
C# , ,
. (Output).
42 1 C#
,
(View).
, -
:
1>------ : : TestHello, : Debug Any CPU ------
1> TestHello -> C:\Users\\Documents\Microsoft Press\VCSBS\Chapter 1\
TestHello\TestHello\bin\Debug\TestHello.exe
========== : : 1, : 0, : 0,
- ,
(Error List). .1.7 , ,
Hello World WriteLine. -
,
.
. 1.7
, ,
. , Visual
Studio ,
.
43
,
.
, -
.
, ,
, .
. 1.8
(Press
any key to continue) Visual Studio,
. (Start
Debugging) , , -
, .
, , -
, ( ), -
. , Visual
Studio2015.
(Solution Explorer) (
) TestHello,
44 1 C#
. 1.9
Release.
Debug. ,
TestHello.exe. ,
. -
, Visual Studio 2015
(Start Debugging).
45
.
-
. .
-, ,
. -, ,
, ,
.
- . , ,
.
, , -
, .
, -
- (
). ,
. , -
, (,
) ,
.
(namespaces)
, . -
,
. namespace,
TestHello
Greeting:
namespace TestHello
{
class Greeting
{
...
}
}
Greeting -
TestHello.Greeting.
Greeting, , NewNamespace, -
, , ,
, TestHello.
Greeting. Greeting ,
NewNamespace.Greeting.
46 1 C#
-
, Visual Studio 2015 ,
.
.NET Framework ,
. ,
Console System. ,
System.Console.
, ,
System.Console. ,
using. TestHello Visual
Studio 2015 Program.cs,
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using.
. -
, .
, ,
Visual Studio 2015 using
. ,
using.
Program.cs
using:
//using System;
. ,
"Console" .
47
. ,
, Program.cs -
.
Main -
System.Console. Main :
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
}
System IntelliSense
, System.
.
. , , Main
, , .
, ,
(Start Without Debugging) .
Hello World! ,
Visual Studio 2015.
using
. .
,
.dll, , , -
.exe .
. , -
.NET Framework, System.Console,
, Visual Studio. -
, .NET Framework .
,
. ( Microsoft
,
!)
.NET Framework ,
, -
. , (mscorlib.dll)
48 1 C#
, System.Console,
, -, GUI-
.. ,
. -
using,
.
, -
:
, , -
. ,
System ,
, , mscorlib.dll, System.dll System.Core.dll.
, .
Visual Studio ,
. -
, TestHello.
,
Microsoft.CSharp, System, System.Core, System.Data, System.Data.
DataSetExtensions, System.Net.Http, System.Xml System.Xml.Linq. ,
mscorlib.dll. ,
.NET Framework ,
.
,
.
,
,
(Add Reference). -
. ,
(Remove).
, Visual Studio 2015
.
Windows10.
Windows
( Universal Windows Platform, UWP-), -
,
Windows: , .
(UI) Windows-
49
XAML
Extensible Application Markup Language. -
Windows Universal Windows Platform
(GUI) . -
XAML .
Hello.
OK.
UWP- ,
Windows 10 (.1.10).
, , Windows 10
,
.
50 1 C#
. 1.10
UWP-
UWP- Visual Studio.
. -
-
. , MainPage.xaml,
C# MainPage.xaml.cs.
, ,
MainPage.xaml.
MainPage.xaml.
.
(.1.11).
,
5- ,
XML- XAML, -
UWP- .
, XML, XAML .
-
XAML-,
.
,
.
51
. 1.11
, -
. Windows-
,
, Universal Windows Platform, -
.
, ,
Visual
Studio 2015, , , .
-
, , .
, C#, Visual
Studio2015 .
(Toolbox),
, -
, .
XAML (Common XAML Controls),
, .
52 1 C#
XAML (All XAML Controls).
TextBlock
, .
TextBlock TextBox.
, ,
Del.
TextBlock,
( ),
.
, ,
, -
(Auto Hide), .
Visual Studio 2015,
, . ( ,
.)
,
.
, TextBlock ,
. ,
. TextBlock . (
.) ,
- , ,
.
XAML- -
TextBlock , ,
Margin, ,
Text,
, , -
HorizontalAlignment VerticalAlignment,
, .
XAML- TextBlock ( -
TextBlock
Margin ):
XAML
. XAML,
. , -
TextBlock, Margin.
(View) (Properties Window).
,
.
XAML ,
.
. , -
( TextBlock),
Grid. XAML, ,
TextBlock Grid.
. , ,
, Grid .
TextBlock,
.
Text. FontSize, -
20 pt, .
,
SegoeUI (.1.12).
FontSize
. 1.12
54 1 C#
pt , ,
1 1/72 .
TextBlock
XAML, .
, FontSize= "26.667 ". ,
(, 3 4, -
).
, , XAML-
, .
FontSize XAML 24. -
TextBlock
.
TextBlock. -
, .
,
TextBlock XAML. -
,
XAML, .
Text TextBlock TextBlock
, . Text
XAML, ,
(Common). ,
TextBlock .
,
. -
TextBox, . -
TextBlock.
-
,
.
.
TextBox. , -
.
TextBox
TextBlock, ,
.
55
TextBox
Name textBox userName (.1.13).
Name
. 1.13
-
2 ,
.
-
Button, .
TextBox, .
, Name Button ok -
Content Button OK,
. , Button
OK.
(.1.14).
,
.
19201080.
, -
.
13,3, -
.
, -
.
56 1 C#
. 1.14
, .1.15 -
(Local Machine). (
Device,
Windows phone, .)
.
. 1.15
,
(.1.16).
,
OK, . ,
OK,
, .
57
. 1.16
UWP-
.
, -
,
(, ).
, .
, ,
.
, Visual
Studio, ( X -
).
,
C#.
( ),
Visual Studio 2015 ,
,
, .
,
Visual Studio .
.
UWP-
MainPage.xaml,
MainPage.xaml.cs.
:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
58 1 C#
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// " " .
// http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace Hello
{
/// <summary>
/// ,
/// .
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
using,
, UWP-,
MainPage.
MainPage, , -
InitializeComponent.
, .
.
7.
, ,
MainPage.xaml.cs, -
XAML- .
,
.
C# UWP-
, .
: Main
? , Main -
.
.
59
App.xaml. , ,
App.xaml.cs. UWP- App.xaml
, .
App.xaml.cs,
, :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Hello
{
/// <summary>
/// ,
/// Application .
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// .
///
/// , main()
/// WinMain().
/// </summary>
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// .
/// ,
/// , .
/// </summary>
/// <param name="e"> .</param>
60 1 C#
// ,
// ,
if (rootFrame == null)
{
// , ,
//
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState ==
ApplicationExecutionState.Terminated)
{
//TODO:
//
}
//
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
//
// ,
//
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
//
Window.Current.Activate();
}
/// <summary>
///
/// </summary>
/// <param name="sender">,
/// </param>
/// <param name="e"> </param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " +
e.SourcePageType.FullName);
}
61
/// <summary>
/// .
/// ,
/// .
/// </summary>
/// <param name="sender"> .</param>
/// <param name="e"> .</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO:
//
deferral.Complete();
}
}
}
(,
///) , , -
OnLaunched, -
. ,
Frame,
MainPage, .
, ,
.
,
, - -
.
OK.
MainPage.xaml, .
OK, .
(Event Handlers button for the selected element).
(.1.17).
.
, , , ,
.
, Click, okClick
. MainPage.xaml.cs ,
62 1 C#
. 1.17
MainPage okClick,
:
private void okClick(object sender, RoutedEventArgs e)
{
, -
3. using
( ,
):
using System;
...
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
okClick , :
private void okClick(object sender, RoutedEventArgs e)
{
MessageDialog msg = new MessageDialog(", " + userName.Text);
msg.ShowAsync();
}
, OK.
,
,
. ,
63
, Visual Studio 2015.
, Visual Studio :
, -
. await . ,
, -
, .NET
Framework. .
,
MainPage.xaml, .
XAML- , ,
Button, . -
, Click,
okClick:
<Button x:Name="ok" ... Click="okClick" />
.
OK. ,
(.1.18).
. 1.18
64 1 C#
:
Visual Studio 2015 .
- Visual C#.
.
.
OK
-
Visual Studio 2015 : . -
UWP- Visual
C#Windows.
( -
Windows).
.
OK
2 ,
, :
, ;
;
;
, (+)
();
.
1 C#
Microsoft Visual Studio 2015
. -
Microsoft Visual C#, ,
.
, C#, , -
. ,
(
), C#
,
, , .
, - ,
. .
3
66 2 ,
, , -
.
main, .
C# , -
.
( ,
).
C# , -
. , 1 ,
:
Console.WriteLine("Hello, World!");
C# , ,
, , ,
. , -
.
, -
.
,
.
.
C#.
,
, , ,
. ( , .) -
C# .
( ),
.
.
C# , :
footballTeam FootballTeam .
67
C# 77 , -
. -
, .
class, namespace using.
C#.
.
C# , . -
C#, ,
, ,
.
68 2 ,
, .
,
.
,
. -
. ,
,
cost .
cost
.
-
.
, ,
, -
,
. -
.
.
C#, -
, , Microsoft Visual Basic.
, -
. , -
myVariable, MyVariable,
69
. , ,
, -
,
, , ,
, Visual Basic.
.
, , -
. (
, , -, camelCase.)
. (
Microsoft Visual C++, , , .
, ,
!)
, score, footballTeam, _score FootballTeam
, .
. C#
, .
: , . -
.
.
, ,
age int (integer). , -
:
int age;
, int, C#,
integer, . (
.)
Visual Basic, , , ,
C# .
.
. -
age 42.
:
age = 42;
70 2 ,
(=) ,
, , ,
. age -
.
age (42) :
Console.WriteLine(age);
C# ,
. C#
.2.1.
2.1
-
,
, ,
.
, C C++,
, . C# -
. -
, ,
.
. ,
: "Use of unassigned local variable
'age'" ( 'age' ), -
Console.WriteLine
:
int age;
Console.WriteLine(age); //
C# PrimitiveDataTypes.
,
Visual Studio 2015 ,
. .
\Microsoft Press\VCSBS\Chapter 2\PrimitiveDataTypes,
. PrimitiveDataTypes,
. ,
PrimitiveDataTypes.
.sln, Primitive
DataTypes.sln. .
Visual C# .csproj. , ,
Visual Studio 2015 .
, , -
.
.
72 2 ,
Visual Studio ,
. (
.)
. 2.1
PrimitiveDataTypes,
MainPage.xaml.
.
73
,
, -
Ctrl+Alt+= Ctrl+Alt+-
(Zoom) .
XAML ,
ListBox.
, (
):
<ListBox x:Name="type" ... SelectionChanged="typeSelectionChanged">
<ListBoxItem>int</ListBoxItem>
<ListBoxItem>long</ListBoxItem>
<ListBoxItem>float</ListBoxItem>
<ListBoxItem>double</ListBoxItem>
<ListBoxItem>decimal</ListBoxItem>
<ListBoxItem>string</ListBoxItem>
<ListBoxItem>char</ListBoxItem>
<ListBoxItem>bool</ListBoxItem>
</ListBox>
ListBox
ListBoxItem.
, SelectionChanged (
1 Click, , -
). , ListBox
typeSelectionChanged. MainPage.xaml.cs.
. ,
MainPage.xaml.cs.
,
. MainPage.xaml,
, MainPage.xaml.cs.
typeSelectionChanged.
, -
(Edit) (Find And Replace),
(Quick Find). -
. -
, (
, ) (.2.2).
.
, ( Aa),
, .
Ctrl+F.
Ctrl+H.
74 2 ,
. 2.2
-
, (.2.3).
. 2.3
75
-
. (
.)
typeSelectionChanged,
typeSelectionChanged.
-
, typeSelectionChanged, ,
4 -
. ,
ListBox
,
, . ,
float, showFloatValue.
, showFloatValue, :
private void showFloatValue()
{
float floatVar;
floatVar = 0.42F;
value.Text = floatVar.ToString();
}
. -
floatVar, float.
floatVar 0.42F.
F , , 0,42
. -
F, 0,42
,
,
C# .
.
. 1,
Text ( 1 XAML).
, .
,
, . (
Console.WriteLine 1?) , ,
Text, , . Text
. , .NET Framework
ToString.
76 2 ,
,
int. showIntValue
,
:
private void showIntValue()
{
int intVar;
intVar = 42;
value.Text = "to do";
}
intVar, -
int.
42. "to do"
intVar.ToString();.
:
private void showIntValue()
{
int intVar;
intVar = 42;
value.Text = intVar.ToString();
}
. .
int. , -
Sample Value 42. Visual Studio,
.
77
showDoubleValue. ,
, ,
, :
private void showDoubleValue()
{
double doubleVar;
doubleVar = 0.42;
value.Text = doubleVar.ToString();
}
showIntValue, , -
doubleVar, ,
0,42.
showBoolValue. ,
:
private void showBoolValue()
{
bool boolVar;
boolVar = false;
value.Text = boolVar.ToString();
}
, ,
boolVar , true false.
false.
.
float, double bool. ,
Sample Value .
Visual Studio,
.
C# , :
(+) , () , (*)
(/) . +, , * /
,
. moneyPaidToConsultant -
750 ( ) 20 (
):
long moneyPaidToConsultant;
moneyPaidToConsultant = 750 * 20;
78 2 ,
, , -
. 750 * 20, * , 750
20 .
. -
, . ,
char, int,
long, float, double decimal. ,
(+),
string
bool. , , -
string (
):
//
Console.WriteLine("Gillingham" - "Forest Green Rovers");
+.
, -
. ,
431 ( 44):
Console.WriteLine("43" + "1");
, -
, .NET Framework -
Int32.Parse,
.
C# ,
, -
+ .
, .
1. okClick
:
MessageDialog msg = new MessageDialog("Hello " + userName.Text);
79
:
MessageDialog msg = new MessageDialog($"Hello {userName.Text}");
$ ,
{ } , -
. $
{username.Text} .
, +.
( + , -
.NET Framework , .)
,
.
,
. ,
5.0/2.0 2.5, double, , -
double. ( C#
double, float,
.) 5/2 2.
int, ,
int.
C# .
. , -
5/2.0 int double. C# -
, int double
. double (2.5).
,
.
C# -
, (%).
x % y x y.
, 9 % 2, , 1, , 9
2, 4, 1.
C C++, ,
float double . C# .
, -
. ,
7.0 % 2.4 2.2.
80 2 ,
C# ,
. ,
, int, long decimal, -
, , 5/0,
. double float ,
, 5.0/0.0 Infinity.
0.0/0.0.
- ,
. 0.0/0.0
-
. C# ,
NaN not a number ( ). ,
0.0/0.0 NaN.
NaN Infinity .
10+NaN, NaN,
10+ Infinity, Infinity.
Infinity*0 NaN.
-
int.
MathsOperators
Visual Studio 2015 MathsOperators,
\Microsoft Press\VCSBS\Chapter 2\MathsOperators .
.
(.2.4).
Left Operand ( ) 54, Right Operand
( ) 13. -
. Subtraction (),
Calculate (). Expression ()
54 13, Result () 0, , , .
/ Division (), Calculate.
Expression 54/13, Result 0.
/ Remainder ( ),
Calculate. Expression 54%13, Result
81
. 2.4
0. , ,
0.
,
,
(Input string was not in a correct format). -
,
6 .
, Visual Studio,
.
, MathsOpe
rators . -
.
MathsOperators
MainPage.xaml (
MainPage.xaml, MathsOperators).
(Other Windows),
(Document Outline).
,
.
.
82 2 ,
, Page, -
. 1, -
Windows (Universal Windows Platform (UWP))
Grid , Grid-
. Grid,
, Grid (
Grid , Grid -
, ). Grid-,
(.2.5).
. 2.5
,
. ,
,
. ( , -
,
, (Auto Hide)
.)
TextBox, -
. ,
lhsOperand rhsOperand. Text
, .
, TextBlock, -
, expression
83
TextBlock,
, result.
. ,
MainPage.xaml.cs.
addValues. :
private void addValues()
{
int lhs = int.Parse(lhsOperand.Text);
int rhs = int.Parse(rhsOperand.Text);
int outcome = 0;
// TODO: Add rhs to lhs and store the result in outcome
expression.Text = $"{lhsOperand.Text} + {rhsOperand.Text}";
result.Text = outcome.ToString();
}
int lhs
, -
, lhsOperand. ,
Text TextBox , lhs
int, ,
lhs, . int -
int.Parse, .
int rhs -
, rhsOperand,
int.
int outcome.
, ,
rhs lhs outcome.
, , .
, ,
, expression.
Text, Expression .
, -
Text Result. , Text
string, int, ,
Text, int
string. ToString, -
int.
addValues -
, :
84 2 ,
MathsOperators
,
.
54 Left Operand 13 Right Operand,
+ Addition, Calculate. Result 67.
, -
. ,
+ *:
2 + 3 * 4
86 2 ,
:
, ?
, .
, , -
(2+3) *
54, 20.
, , -
(34) +
2+12, 14.
C# (*, / %) -
(+ ), , , 2+34,
, .
2+34 14.
-
. ,
2 3 +
( 5)
*, 20:
(2 + 3) * 4
(). -
{ }. -
[ ].
. :
, ,
? -
, ( ), -
. ,
/ *:
4 / 2 * 6
-
. , ?
(
87
), ,
.
, (4/2)
*, (4/2)6, 12.
, (26)
/ ,
4/(26), 4/12.
-
. , * /, , ,
. 4/2 -
6, 12.
C# (=) . -
. =
. : ,
, .
, . ,
,
, 10, , -
myInt:
int myInt;
myInt = 10; // 10
: , , ,
? ,
:
int myInt;
int myInt2;
myInt2 = myInt = 10;
, myInt2, ,
myInt.
. , -
. ,
, ,
:
myInt5 = myInt4 = myInt3 = myInt2 = myInt = 10;
88 2 ,
, , -
.
,
. - ,
.
.
, C#
-
. , ,
(10):
int myInt, myInt2, myInt3 = 10;
C# ( ). -
myInt, myInt2 myInt3 myInt3
10. myInt myInt2.
myInt myInt2 :
myInt3 = myInt / myInt2;
, -
, :
Use of unassigned local variable 'myInt'
Use of unassigned local variable 'myInt2'
1, , ,
+:
count = count + 1;
1 ( )
, C# ++. -
count 1,
:
count++;
C# --,
1 :
count--;
89
++ -- , ,
. -
( ).
(++) (--) ,
, .
,
. :
count++; //
++count; //
count--; //
--count; //
, , ++ -- -
, ,
. ,
count++, count , ++count,
. , , , :
? -
, , ++ --
, . , -
count++, count ,
, ++count, count
. :
int x;
x = 42;
Console.WriteLine(x++); // x 43, 42
x = 42;
Console.WriteLine(++x); // x 43, 43
, ,
( ) -
. x++ , ,
. ++x , ,
, x .
while do, -
5 -
. ,
.
90 2 ,
,
:
int myInt;
,
.
, :
int myInt = 99;
, ,
myOtherInt :
, , ,
, . , int
int. C#
, ,
, .
, var
C#
:
var myVariable = 99;
var myOtherVariable = "Hello";
myVariable myOtherVariable -
. var
, .
myVariable int, myOtherVariable string.
,
, ,
. ,
myVariable float, double string.
, var
, . -
:
var yetAnotherVariable; //
91
,
Visual Basic, Variant,
.
, , -
Variant Visual Basic. var Variant
, . -
C# var ,
, , .
, , , , ,
, C#,
, var.
, ,
(
). , var
C# , ,
. -
,
.
, , -
,
C#. . , -
,
.
,
Visual Studio 2015 3.
Visual Studio 2015,
(Exit).
, (Yes) .
, -
, , :
int outcome;
92 2 ,
, -
, -
. -
, :
int outcome = 99;
- , -
, ,
, -
, :
outcome = 42;
, - ToString, -
, - :
int intVar = 42;
string stringVar = intVar.ToString();
System.Int32.Parse, :
string stringVar = "42";
int intVar = System.Int32.Parse(stringVar);
- -
, :
(3 + 4) * 5
, -
- , :
myInt4 = myInt3 = myInt2 = myInt = 10;
++ --, :
count++;
3
, :
;
;
;
;
.
2 , ,
,
,
, .
. , ,
return .
, Microsoft Visual Studio 2015
.
,
.
, , -
, .
94 3
.
, C,
C++ Microsoft Visual Basic, ,
. .
,
(, , ,
calculateIncomeTax). ,
. , ,
,
.
.
C# :
returnType methodName ( parameterList )
{
// ,
}
:
returnType , ,
.
, int string. ,
,
void ();
methodName , . -
, . ,
addValues , add$Values .
-
(camelCase), displayCustomer;
parameterList ,
, -
.
, ( ), , ,
, .
,
;
95
, , -
.
, { }.
addValues,
int int-, leftHandSide rightHandSide:
int addValues(int leftHandSide, int rightHandSide)
{
// ...
// ,
// ...
}
, -
. var .
showResult, -
int answer:
void showResult(int answer)
{
// ...
}
void,
, .
Visual Basic, , C# -
, ,
(), , ( ).
C# , void.
, ( -
void),
return.
return, ,
, .
, . ,
96 3
int, , return
int, .
return:
int addValues(int leftHandSide, int rightHandSide)
{
// ...
return leftHandSide + rightHandSide;
}
return , -
,
, . ,
return, ( -
return, ).
(
void),
return, .
return , :
void showResult(int answer)
{
//
Console.WriteLine($"The answer is {answer}");
return;
}
, -
return, ,
.
, .
-
,
- . ,
, C# .
, , .
addValues showResult,
-:
int addValues(int leftHandSide, int rightHandSide) => leftHandSide + rightHandSide;
void showResult(int answer) => Console.WriteLine($"The answer is {answer}");
97
, , =>
return. ,
, , -
void.
-
, -
. , --
,
{ } .
MathsOperators 2. -
.
.
Visual Studio 2015 Methods,
\Microsoft Press\VCSBS\ Chapter 3\Methods .
private
; , ,
7 .
addValues . -
, -
int- + int- leftHandSide
98 3
rightHandSide, . ,
int- int-, ,
addValues int.
subtractValues, multiplyValues, divideValues remain
derValues, , .
showResult, :
private void showResult(int answer) => result.Text = answer.ToString();
-, , -
, , answer.
, void.
.
, ,
.
, -
.
,
, .
, . -
, .
( ), .
, -
, - .
C# :
result = methodName ( argumentList )
, .
methodName
. , C#
.
result = . , -
result , .
void- ( , ),
99
result = . , ,
result =, ,
.
argumentList , .
, -
.
, -
.
,
.
, addValues :
int addValues(int leftHandSide, int rightHandSide)
{
// ...
}
addValues int, ,
, -
int:
addValues(39, 3); //
39 3 int-.
:
int arg1 = 99;
int arg2 = 1;
addValues(arg1, arg2);
addValues - , ,
, , -
:
addValues; // ,
addValues(); // ,
addValues(39); // ,
addValues("39", "3"); // ,
Methods.
.
Methods. MainPage.xaml.
cs. calculateClick
try . (
try 6 .)
:
int leftHandSide = System.Int32.Parse(lhsOperand.Text);
int rightHandSide = System.Int32.Parse(rhsOperand.Text);
int- leftHandSide
rightHandSide. .
Parse System.Int32. (System
, Int32 .
9
.) ,
int-.
,
lhsOperand rhsOperand, int.
calculateClick ( -
if ):
calculatedValue = addValues(leftHandSide, rightHandSide);
addValues,
leftHandSide rightHandSide. ,
addValues, calculatedValue.
:
showResult(calculatedValue);
showResult,
calculatedValue. showResult .
showResult. -
:
result.Text = answer.ToString();
, ToString
, .
101
, , , -
. answer.ToString()
ToString, answer.
. -
. , calculateClick
Methods int- calculatedValue
0:
private void calculateClick(object sender, RoutedEventArgs e)
{
int calculatedValue = 0;
...
}
, ,
calculateClick -
. :
. ,
- .
, ,
.
calculatedValue ,
calculateClick, .
, -
, ,
. ,
.
, ,
.
, . ,
( ) -
, .
, . ,
, ,
. ,
102 3
. , -
, ,
.
, -
.
:
class Example
{
void firstMethod()
{
int myVar;
...
}
void anotherMethod()
{
myVar = 42; //
...
}
}
, anotherMethod
myVar, .
myVar firstMethod, -
, myVar.
, . , -
( ),
. C# , , -
. , -
, .
:
class Example
{
void firstMethod()
{
myField = 42; // ok
...
}
void anotherMethod()
{
myField++; // ok
...
}
int myField = 0;
}
103
myField , firstMethod
anotherMethod. myField ,
.
. -
.
. ,
, -
.
, .
, -
. ,
, . ,
, . -
, , ,
. ,
.
WriteLine Console.
. C# WriteLine
, Microsoft IntelliSense
19 ! WriteLine
: -
, ,
(True False),
..
,
,
. :
static void Main()
{
Console.WriteLine("The answer is ");
Console.WriteLine(42);
}
,
. ,
104 3
,
,
. ,
, -
.
, , ,
, , -
. ,
,
. (, , ,
.)
, ,
-
. ,
Generate Method
Stub Wizard, , . ,
,
. , Visual Studio 2015, -
.
Visual Studio 2015 DailyRate,
\Microsoft Press\VCSBS\Chapter 3\DailyRate . -
DailyRate Program.cs,
.
.
, run. run
, . ( ,
, 7.)
run
, :
void run()
{
double dailyRate = readDouble("Enter your daily rate: ");
int noOfDays = readInt("Enter the number of days: ");
writeFee(calculateFee(dailyRate, noOfDays));
}
105
, run, readDouble
( ), ,
. readInt (
), . , -
writeFee ( )
. , , writeFee,
, calculateFee ( -
),
.
Generate Method Stub Wizard
, run, readDouble
. , ,
(.3.1).
. 3.1
106 3
(Quick Actions).
Visual Studio , readDouble , -
, . Visual Studio
readDouble, -
(.3.2).
. 3.2
private, -
7. NotImplementedException.
( 6.)
.
107
, v.
, ,
.
Console.Write Console.WriteLine,
, ,
.
,
ReadLine ,
double.Parse.
.
ReadLine - WriteLine,
,
. , ,
. .
run readInt, -
,
"Program.readInt".
readInt:
private int readInt(string v)
{
throw new NotImplementedException();
}
readDouble. -
, int, ,
, , ,
int.Parse.
calculateFee,
, "Program.
calculateFee".
calculateFee:
private object calculateFee(double dailyRate, int noOfDays)
{
throw new NotImplementedException();
}
, Visual Studio
. (,
, .)
, , -
object. Visual Studio ,
,
. object ,
. object -
7.
calculateFee , , -
,
:
private double calculateFee(double dailyRate, int noOfDays)
{
throw new NotImplementedException();
}
calculateFee -
, . -
:
private double calculateFee(double dailyRate, int noOfDays) => dailyRate *
noOfDays;
writeFee,
run, ,
"Program.writeFee".
: Visual Studio, ,
double, writeFee.
109
, ,
void:
private void writeFee(double v)
{
...
}
, ,
.
.
writeFee ,
10% .
, , -:
private void writeFee(double v) => Console.WriteLine($"The consultant's fee is:
{v * 1.1}");
Visual Studio 2015 -
.
,
. ,
, ,
, (Extract
Method). NewMethod.
, -
- .
- ,
, , ,
.
(Start Without Debugging).
Visual Studio 2015 ,
. .
Enter Your Daily Rate 525 .
Enter The Number of Days 17 .
110 3
-
:
The consultant's fee is: 9817,5
, Visual Studio2015.
Visual Studio 2015. , ,
( ),
, return
( ).
-
, .
, .
VisualStudio2015
run.
:
double dailyRate = readDouble("Enter your daily rate: ");
,
(Run To Cursor).
, -
run, .
,
(.3.3).
(Toolbars) ,
(Debug toolbar) . ,
. -
. , -
,
( ), , .
.
(.3.4).
(Step Into)
( ). -
.
readDouble.
111
. 3.3
. 3.4
, -
:
Console.Write(v);
F11.
112 3
(Step Over) (
). (
). ,
,
.
, Visual Studio 2015
. ( -
Visual Studio.)
,
F10.
.
,
Console.ReadLine , - -
. 525 .
Visual Studio 2015.
.
line
(, ). ,
line ("525"). ,
-
(.3.5).
. 3.5
(Step Out) (
).
. readDouble ,
run. .
,
Shift+F11.
113
. -
run:
int noOfDays = readInt("Enter the number of days: ");
.
.
. 17
. Visual Studio 2015 (,
).
run:
writeFee(calculateFee(dailyRate, noOfDays));
.
, calculateFee. -
writeFee, , ,
writeFee .
. calculateFee
, -
run.
. -
, writeFee.
v.
v, 8925.
.
The consultant's fee is: 9817,5. (
Visual Studio 2015, .)
run.
(Continue),
-
.
,
(Add Or Remove Buttons),
, .
. -
F5.
.
,
,
.
114 3
, -
, .
, , ,
-
. --
, C#. Windows-
,
. C# ,
.NET Framework, -
,
. ,
Windows- , .NET Framework, -
(Component Object Model (COM)).
, (common language runtime (CLR)),
.NET Framework, COM,
Windows Runtime Windows10.
COM , -
, .
COM- C#,
C# .
.
-
, -
. , , :
public void DoWorkWithData(int intData, float floatData, int moreIntData)
{
...
}
DoWorkWithData : int
float. ,
DoWorkWithData , : intData floatData .
:
public void DoWorkWithData(int intData, float floatData)
{
...
}
115
, DoWorkWithData,
, , -
, -
:
int arg1 = 99;
float arg2 = 100.0F;
int arg3 = 101;
, -
DoWorkWithData, .
:
public void DoWorkWithData(int intData)
{
...
}
public void DoWorkWithData(int moreIntData)
{
...
}
, -
. ,
, , -
DoWorkWithData .
, , , -
. :
int arg1 = 99;
int arg3 = 101;
DoWorkWithData(arg1);
DoWorkWithData(arg3);
,
DoWorkWithData?
.
-
.
116 3
. optMethod
, -
, :
void optMethod(int first, double second = 0.0, string third = "Hello")
{
...
}
-
.
, ,
, :
. , -
, ,
, -
.
optMethod .
,
.
"Hello":
optMethod(99, 123.45, "World"); //
optMethod(100, 54.321); //
C#
, .
OptMethod, ,
first second,
. C#
. -
.
, .
,
, , :
optMethod(first : 99, second : 123.45, third : "World");
optMethod(first : 100, second : 54.321);
. optMethod :
117
. ,
optMethod -
, :
optMethod(first : 99, third : "World");
, .
,
:
optMethod(99, third : "World"); //
,
. ,
,
. , -
optMethod , :
void optMethod(int first, double second = 0.0, string third = "Hello")
{
...
}
void optMethod(int first, double second = 1.0, string third = "Goodbye",
int fourth = 100 )
{
...
}
C#, -
. ,
. ,
optMethod ,
, -
:
optMethod(1, 2.5, "World");
, optMethod
? : ,
118 3
. , , ,
. :
optMethod(1, fourth : 101);
optMethod
, . -
optMethod, ,
. :
optMethod(1, 2.5);
optMethod.
, .
: ,
, ,
-
? : . -
, .
optMethod
:
optMethod(1, third : "World");
optMethod(1);
optMethod(second : 2.5, first : 1);
, , -
. -
C# ,
.
, -
. ,
calculateFee. (
.)
private double calculateFee(double dailyRate = 500.0, int noOfDays = 1)
{
Console.WriteLine("calculateFee using two optional parameters");
return dailyRate * noOfDays;
}
Program calculateFee,
, .
dailyRate double.
, :
private double calculateFee(double dailyRate = 500.0)
{
Console.WriteLine("calculateFee using one optional parameter");
int defaultNoOfDays = 1;
return dailyRate * defaultNoOfDays;
}
Program calculateFee.
:
private double calculateFee()
{
Console.WriteLine("calculateFee using hardcoded values");
double defaultDailyRate = 400.0;
int defaultNoOfDays = 1;
return defaultDailyRate * defaultNoOfDays;
}
run , ,
calculateFee :
public void run()
{
double fee = calculateFee();
Console.WriteLine($"Fee is {fee}");
}
-
. ,
(Peek Definition).
calculateFee .3.6.
120 3
. 3.6
,
, .
,
. -
:
calculateFee using hardcoded values
Fee is 400
run calculateFee, ,
, ,
. ,
Visual Studio.
run , calculateFee, -
, :
public void run()
{
double fee = calculateFee(650.0);
Console.WriteLine($"Fee is {fee}");
}
121
,
. :
calculateFee using one optional parameter
Fee is 650
run calculateFee, -
. ,
. , -
Visual Studio.
run , calculateFee:
public void run()
{
double fee = calculateFee(500.0, 3);
Console.WriteLine($"Fee is {fee}");
}
,
. :
calculateFee using two optional parameters
Fee is 1500
, run
calculateFee, .
, Visual Studio.
run , calculateFee,
dailyRate :
,
. :
calculateFee using one optional parameter
Fee is 375
run calculateFee, -
.
,
. , -
Visual Studio.
122 3
run , calculateFee,
noOfDays:
public void run()
{
double fee = calculateFee(noOfDays : 4);
Console.WriteLine($"Fee is {fee}");
}
,
. :
calculateFee using two optional parameters
Fee is 2000
run calculateFee, -
. (dailyRate)
.
calculateFee, .
, Visual Studio.
calculateFee, -
. theDailyRate
return, ,
:
private double calculateFee(double theDailyRate = 500.0, int noOfDays = 1)
{
Console.WriteLine("calculateFee using two optional parameters");
return theDailyRate * noOfDays;
}
run , calculateFee,
theDailyRate :
,
. :
calculateFee using two optional parameters
Fee is 375
, , -
, run calculateFee,
. run calculateFee,
123
.
, . -
, ,
, ,
. calculateFee
aDailyRate: 375.0, , -
,
. ,
Visual Studio.
, -
. ,
. ,
, . ,
,
, ,
. Visual Studio 2015 -
. , , , -
,
.
,
Visual Studio 2015 4
.
Visual Studio 2015,
. -
, .
. ,
,
, , :
int addValues(int leftHandSide, int rightHandSide)
{
...
}
124 3
return, :
return leftHandSide + rightHandSide;
return , :
return;
- =>,
, ,
, :
double calculateFee(double dailyRate, int noOfDays)=>
dailyRate * noOfDays;
, -
, :
addValues(39, 3);
,
-
(Generate Method
Stub Wizard)
- -
-
- , :
void optMethod(int first, double second = 0.0,
string third = "Hell")
{
...
}
- , :
optMethod(first : 100, third : "World");
4
, :
;
,
true false;
if
;
switch .
3 ,
. , -
,
return .
,
, .
. -
.
, 3, ,
.
, -
, . , ,
.
126 4
C#-, , ,
, , , (true),
(false). , x,
99, , x 99,
(true). , , x
10, (false).
, true false.
.
, , , ,
10. , C C++,
. Microsoft Visual C#
,
. -
.
, , -
true, false. C#
, NOT,
(!). ! ,
. ,
areYouReady true, !areYouReady false.
,
, (==) (!=). ,
, ,
127
, .
int- age .4.1.
4.1
,
age 42
== age == 100 false
!= age != 0 true
== =. -
x==y x y true, .
x=y y x
y.
== != -
. , ,
.
.4.2.
4.2
,
age 42
C# :
, &&,
, ||.
.
.
, ,
, , , ,
, , ,
.
128 4
&& true ,
true. , -
true validPercentage
, percent 0
100:
bool validPercentage;
validPercentage = (percent >= 0) && (percent <= 100);
,
percent :
percent >= 0 && <= 100 //
,
. ,
validPercentage = percent >= 0 && percent <= 100
validPercentage = (percent >= 0) && (percent <= 100)
, && ,
>= <=.
.
|| true ,
true. ||
, true.
, true
invalidPercentage , percent 0
100:
bool invalidPercentage;
invalidPercentage = (percent < 0) || (percent > 100);
, &&, ||,
.
. ,
&& false, false
. ,
|| true,
true .
&& || .
.
if 129
(percent >= 0) && (percent <= 100)
percent , -
&& false. ,
false, &&
.
(percent < 0) || (percent > 100)
percent , -
|| true. ,
true, ||
.
, -
, , .
, -
, .
, .
.4.3 -
.
. ,
,
, .
, && || : &&
, ||.
if
, -
if.
130 4
4.3
()
++
--
+ -
- -
++
--
- *
/
% -
<
<=
>
>=
==
!=
&&
||
= -
-
-
if 131
if
if (if else
C#):
if ( booleanExpression )
statement-1;
else
statement-2;
booleanExpression true, -
statement-1, statement-2.
else statement-2 -
. else booleanExpression
false, , ,
if. ,
, .
, , if, ,
, (
). seconds 59, -
0, -
++:
int seconds;
...
if (seconds == 59)
seconds = 0;
else
seconds++;
, !
if .
, . , -
C C++, ,
true ( )
false ( ). C#
.
if (==)
(=), C# , -
, :
int seconds;
...
if (seconds = 59) //
...
if (seconds == 59) //
132 4
C C++, (59)
(
true), ,
if, .
, if -
, , ,
:
bool inWord;
...
if (inWord == true) // ,
...
if (inWord) //
, if
if (booleanExpression) else
. , true,
. , ,
, ,
, -
,
.
,
seconds , minutes
, , seconds 59,
:
int seconds = 0;
int minutes = 0;
...
if (seconds == 59)
{
seconds = 0;
minutes++;
}
else
{
seconds++;
}
if 133
, C# -
if (seconds = 0;). -
(minutes++;)
if. ,
else, if, -
.
if ,
. ,
.
.
, ,
.
:
if (...)
{
int myVar = 0;
... // myVar
} // myVar
else
{
// myVar
...
}
// myVar
if-
if if.
, -
, true.
, day ,
true dayName
"Sunday". day , -
else, -
if day .
if ,
.
if ,
:
if (day == 0)
{
dayName = "Sunday";
}
else if (day == 1)
{
134 4
dayName = "Monday";
}
else if (day == 2)
{
dayName = "Tuesday";
}
else if (day == 3)
{
dayName = "Wednesday";
}
else if (day == 4)
{
dayName = "Thursday";
}
else if (day == 5)
{
dayName = "Friday";
}
else if (day == 6)
{
dayName = "Saturday";
}
else
{
dayName = "unknown";
}
, ,
if, .
if
Microsoft Visual Studio 2015 Selection,
\Microsoft Press\VCSBS\Chapter 4\Selection .
. Visual Studio 2015
.
firstDate secondDate. -
. Compare ().
, ,
:
firstDate == secondDate : False
firstDate != secondDate : True
firstDate < secondDate : False
firstDate <= secondDate : False
firstDate > secondDate : True
firstDate >= secondDate : True
. .4.1.
. 4.1
, Compare.
firstDate.Date.LocalDateTime secondDate.Date.LocalDateTime
136 4
DateTime, , -
firstDate secondDate .
DateTime , int float,
,
, , .
compareClick dateCompare DateTime.
int- 0,
, 1 +1
. ,
. dateCompare .
show info,
.
dateCompare, :
private int dateCompare(DateTime leftHandSide, DateTime rightHandSide)
{
// TO DO
return 42;
}
, -
, 0, 1 +1 . ,
, .
, .
dateCompare // TO DO return. -
dateCompare ,
:
private int dateCompare(DateTime leftHandSide, DateTime rightHandSide)
{
int result = 0;
.
dateCompare , .
if 137
, , -
.
leftHandSide.Month < rightHandSide.Month false
leftHandSide.Month > rightHandSide.Month
false, Month , -
, .
, ,
dateCompare , , :
}
else
{
result = 0;
}
return result;
}
. -
, leftHandSide.Day < rightHandSide.Day leftHandSide.Day > rightHandSide.
Day, false, Day
. ,
Month Year , ,
result .
,
result.
.
. Compare.
:
firstDate == secondDate : True
firstDate != secondDate : False
firstDate < secondDate: False
firstDate <= secondDate: True
firstDate > secondDate: False
firstDate >= secondDate: True
.
DatePicker
, Compare.
:
firstDate == secondDate: False
firstDate != secondDate: True
firstDate < secondDate: True
firstDate <= secondDate: True
firstDate > secondDate: False
firstDate >= secondDate: False
.
-
, . , -
Visual Studio 2015 .
switch 139
, ,
if else, ,
. dateCompare
, , leftHandSide
rightHandSide, DateTime. ,
, ,
, ,
( ). DateTime ,
, . -
,
DateTime Compare, -
: DateTime ,
, , , ,
; , -
, ;
, .
switch
if- , -
, .
, if-
. , ,
, if day
, :
if (day == 0)
{
dayName = "Sunday";
}
else if (day == 1)
{
dayName = "Monday";
}
else if (day == 2)
{
dayName = "Tuesday";
}
else if (day == 3)
{
...
}
else
{
dayName = "Unknown";
}
140 4
if- -
switch,
.
switch
switch (switch , case
default ):
switch ( controllingExpression )
{
case constantExpression :
statements
break;
case constantExpression :
statements
break;
...
default :
statements
break;
}
controllingExpression,
, .
, constantExpression ,
controllingExpression. (
constantExpression .)
break, switch
, , ,
switch.
constantExpression controllingExpression, -
, default.
constantExpression ,
controllingExpression . -
controllingExpression - constantExpression,
default , -
, switch.
if- ,
switch:
switch (day)
{
case 0 :
dayName = "Sunday";
break;
case 1 :
switch 141
dayName = "Monday";
break;
case 2 :
dayName = "Tuesday";
break;
...
default :
dayName = "Unknown";
break;
}
switch
switch, ,
, . switch-
.
switch ,
int, char string. ( float
double) if.
, -
, , 42, switch int, '4',
char, "42",
string.
, if.
. -
, .
,
, ,
,
.
,
, .
:
switch (trumps)
{
case Hearts :
case Diamonds : // ,
//
color = "Red"; // Hearts Diamonds
break;
case Clubs :
color = "Black";
case Spades : //
color = "Black";
break;
}
142 4
-
break,
, switch, -
return throw, -
switch. throw 6
.
SWITCH
-
- -
, switch,
( default,
,
).
, C C++, ,
break switch (
default). ,
C C++
break,
, .
, C C++, C#,
goto
default. - goto ,
.
, -
XML-
. , ( <) XML
( ).
,
<, XML- , ,
XML-. -
(>), (&), (')
("). switch,
XML,
.
switch
Microsoft Visual Studio 2015 SwitchStatement, -
\Microsoft Press\VCSBS\Chapter 4\SwitchStatement -
.
switch 143
Copy.
, .4.2,
, <, & > .
. 4.2
default. switch
, , XML
, XML. , < -
<.
switch -
default ,
:
switch (current)
{
case '<' :
target.Text += "<";
break;
default:
target.Text += current;
break;
}
(<), -
, , "<".
break default
:
case '>' :
target.Text += ">";
break;
case '&' :
target.Text += "&";
break;
case '\"' :
target.Text += """;
break;
case '\'' :
target.Text += "'";
break;
(') (") C# -
. (\)
, C#
, .
. -
:
inRange = (lo <= number) && (hi >= number);
Copy.
145
.
XML-, switch,
. :
inRange = (lo <= number) && (hi >= number);
, -
(<, >, &, " ') .
Visual Studio .
, , ,
if switch
,
.
,
Visual Studio 2015 5
.
Visual Studio 2015,
.
, .
- answer == 42
== -
!=
- age >= 21
<, <=, > >=
- - bool inRange;
bool
, - if (inRange)
if process();
true
- if (seconds == 59)
, if {
true seconds = 0;
minutes++;
}
- - switch (current)
switch {
case 0:
...
break;
case 1:
...
break;
default :
...
break;
}
5
, :
-
;
while, for do;
do -
.
4 ,
if switch.
, ( )
.
, , -
.
, -
.
, ,
-
.
148 5
. ,
42 answer -
(+):
Console.WriteLine(answer + 42);
, -
. answer
42 (=):
answer = 42;
42 , -
+. ,
answer 42 .
answer 42 , :
, , ,
, . -
, C#
+=. 42 answer -
:
answer += 42;
.5.1 , -
.
.
5.1
= * ; *= ;
= / ; /= ;
= % ; %= ;
= + ; += ;
= - ; -= ;
while 149
-
, (=).
+= ,
. ,
Hello John:
string name = "John";
string greeting = "Hello ";
greeting += name;
Console.WriteLine(greeting);
-
.
, -
,
(++) (--). ,
count += 1;
count++;
while
while
, true. -
:
while ( )
, ,
true, , -
. - true,
,
. , -
false, while.
, while.
while , if
( , ):
.
.
150 5
false,
.
while
, .
while, 0 9.
, i 10,
while :
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
}
- while .
, -
false , -
.
i++;.
i while
. , , , -
-. (
), ,
-, -
, j, k l.
, if, while
,
. , -
while , ,
. , while
, -
, ,
, :
int i = 0;
while (i < 10)
Console.WriteLine(i);
i++;
, -
, while -
Console.WriteLine, i++;.
while
.
while 151
while
Microsoft Visual Studio 2015 WhileStatement,
\Microsoft Press\VCSBS\Chapter 5 \WhileStatement .
. Visual Studio 2015
, -
,
.
Open File ( ). ,
, .5.1, ,
( , -
).
. 5.1
. \Microsoft
Press\VCSBS\Chapter 5\WhileStatement\WhileStatement. MainPage.xaml.cs
.
, MainPage.xaml.cs,
. ,
,
. .
152 5
, -
.
, , -
( FileOpenPicker
OpenFileDialog) .
openFileClick,
:
TextReader reader = new StreamReader(inputStream.AsStreamForRead());
displayData(reader);
TextReader- reader.
TextReader , Microsoft.NET Framework,
-
, . System.IO.
TextReader,
, ,
FileOpenPicker. displayData,
reader. displayData,
reader, (
, ).
displayData. :
private void displayData(TextReader reader)
{
// TODO: add while loop here
}
, , . -
.
// TODO: add while loop here :
source.Text = "";
source .
Text ("") , -
.
displayData -
:
string line = reader.ReadLine();
while 153
line ,
, reader.ReadLine.
, ,
, , null.
displayData
:
while (line != null)
{
source.Text += line + '\n';
line = reader.ReadLine();
}
while, -
, .
while line.
null, , ,
('\n' ReadLine TextReader
,
, ),
Text . ,
, while .
while , ,
ReadLine null.
while -
:
reader.Dispose();
.
,
, , ,
.
. ,
Open File.
\Microsoft Press\VCSBS\Chapter 5\WhileStatement\
WhileStatement , MainPage.xaml.cs,
.
, . ,
.
, , -
.
154 5
,
.
(.5.2).
. 5.2
displayData. ,
.
Visual Studio .
for
C# while -
:
while ( )
{
}
while 155
for C# -
, ,
, .
for ,
,
, -
. for :
for (; ; )
, for,
, .
while,
0 9, for:
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
, . ,
true, .
, -
. - true,
, ,
..
, ,
,
.
, , while,
, for .
-
.
for .
, true
for :
for (int i = 0; ;i++)
{
Console.WriteLine("somebody stop me!");
}
156 5
, ,
- while:
int i = 0;
for (; i < 10; )
{
Console.WriteLine(i);
i++;
}
for, , -
, ,
.
for -
. (
.)
, :
for (int i = 0, j = 10; i <= j; i++, j--)
{
...
}
, while -
for:
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
source.Text += line + '\n';
}
for
, , for
.
for, , -
. . -,
for, -
. :
for (int i = 0; i < 10; i++)
{
...
}
Console.WriteLine(i); //
while 157
-, for,
, ,
, :
for (int i = 0; i < 10; i++)
{
...
}
for (int i = 0; i < 20; i += 2) //
{
...
}
do
while for
. , -
false, . do
-: ,
.
do (
):
do
while ( );
,
( , -
). ,
0 9, do:
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 10);
BREAK CONTINUE
4 break
switch. break -
. ,
, . -
.
158 5
, continue -
( ).
,
0 9, break continue:
int i = 0;
while (true)
{
Console.WriteLine(i);
i++;
if (i < 10)
continue;
else
break;
}
. -
continue
, ,
. continue -
. , continue
for,
, .
do, -
-
. ,
:
dec
dec 8
dec ,
dec
, ,
, , 999
. .
1. 999 8. 124, 7.
2. 124 8. 15, 4.
3. 15 8. 1, 7.
4. 1 8. 0, 1.
5. , ,
. 1747. -
999.
while 159
do
Visual Studio 2015 DoStatement,
\Microsoft Press\VCSBS\Chapter 5\DoStatement .
MainPage.xaml. -
number,
.
Show Steps ( ),
. -
steps.
MainPage.xaml.cs
showStepsClick. ,
Show Steps. .
showStepsClick ,
:
private void showStepsClick(object sender, RoutedEventArgs e)
{
int amount = int.Parse(number.Text);
steps.Text = "";
string current = "";
}
Text
number Parse,
int, amount.
, steps, -
Text .
current -
.
, ,
.
showStepsClick do (
):
private void showStepsClick(object sender, RoutedEventArgs e)
{
int amount = int.Parse(number.Text);
steps.Text = "";
string current = "";
do
{
160 5
-
, amount 8
. -
. ,
amount , . ,
.
, 0 .
, , do
:
int nextDigit = amount % 8;
int- nextDigit -
amount 8.
0 7.
do
amount /= 8;
- . , -
, .
Windows 0 -
48. 1 49, 2 50
9, 57.
C# -
, C# .
, '0' + nextDigit
48 55 (, nextDigit
0 7), .
while 161
do
char digit = Convert.ToChar(digitCode);
digit -
Convert.ToChar(digitCode).
Convert.ToChar , ,
. , digitCode 54, Convert.
ToChar(digitCode) '6'.
, do , -
( ) ,
, .
:
current = digit + current;
do
steps.Text += current + "\n";
steps , ,
.
, , -
.
, while do :
while (amount != 0);
amount ,
.
Visual Studio 2015,
do, , .
do
, MainPage.xaml.cs, -
showStepsClick:
int amount = int.Parse(number.Text);
-
(Run To Cursor).
162 5
, 999
Show Steps ( ).
, Visual Studio 2015.
-
. ,
(
).
, -
.
, -
(Add Or Remove Buttons),
(.5.3).
. 5.3
(Breakpoints
Window).
, -
, (Locals) (.5.4).
( ).
, , ,
amount. ,
amount (.5.5).
.
:
int amount = int.Parse(number.Text);
while 163
. 5.4
. 5.5
amount 999, -
.
. :
steps.Text = "";
, steps
, .
164 5
.
. :
, do.
: nextDigit,
digitCode digit. ,
.
.
do. .
:
int nextDigit = amount % 8;
nextDigit 7.
999 8. .
:
amount /= 8;
amount 124.
. :
int digitCode = '0' + nextDigit;
digitCode 55.
7 (48 + 7). .
:
char digit = Convert.ToChar(digitCode);
digit '7'.
( 55), ('7').
, current
- "". .
:
current = current + digit;
current "7".
. :
steps.Text += current + "\n";"
while 165
steps "7",
,
. ( Visual Studio,
.)
do.
.
while , , do
.
. :
while (amount != 0);
amount , amount
!= 0 false do .
. -
:
while (amount != 0);
, do
showStepsClick.
. , -
999: 7, 47, 747
1747 (.5.6).
Visual Studio 2015.
.
166 5
. 5.6
, -
. , while, for do
,
true.
, -
Visual Studio 2015 6
.
Visual Studio 2015,
. -
, .
167
-
, :
+= ;
, :
-= ;
while, :
int i = 0;
, while (i < 10)
{
true Console.WriteLine(i);
i++;
}
for, :
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
do, :
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 10);
6
, :
try, catch
finally;
checked unchecked;
throw;
-
finally.
C#, -
, , -
, ,
if switch while,
for do , .
( ) , -
.
, -
, . ,
, , .
:
, , ,
.
, C#
,
, try, catch finally.
169
C#, ,
.
, . -
, , ,
,
. , -
,
,
, -
, ,
.
,
. :
?
.
, -
, UNIX,
.
, . C#,
- -
, ,
. .
, C#, ,
, .
, -
, -
, ,
. , C#
,
170 6
. , ,
:
try ( C# ).
, ,
try, ,
.
, ,
try ,
, ;
C#, catche, try,
. -
, try
,
.
,
try. try -
, .
, try,
.
try, ,
, ,
.
.
, , -
.
, int.Parse FormatException
. -
,
. , , -
, (
):
try
{
int leftHandSide = int.Parse(lhsOperand.Text);
int rightHandSide = int.Parse(rhsOperand.Text);
int answer = doCalculation(leftHandSide, rightHandSide);
result.Text = answer.ToString();
}
catch (FormatException fEx)
171
{
//
...
}
-
, , .
FormatException fEx
, .
FormatException ,
.
. , Message -
, .
, ,
-
.
, try , -
? ,
lhsOperand
, ,
C# (, 2147483648).
int.Parse OverflowException,
FormatException. -
try ,
, . -
try,
try
. try
,
, -
, .
,
, ,
.
,
, catch, . -
, ,
, ,
.
172 6
,
.
, , . -
Microsoft Visual Studio 2015 (
) ,
, .6.1,
, .
. 6.1
, -
, .
,
, ,
.
173
, -
.
, -
, :
try
{
int leftHandSide = int.Parse(lhsOperand.Text);
int rightHandSide = int.Parse(rhsOperand.Text);
int answer = doCalculation(leftHandSide, rightHandSide);
result.Text = answer.ToString();
}
catch (FormatException fEx)
{
//...
}
catch (OverflowException oEx)
{
//...
}
try FormatException,
catch, FormatException.
OverflowException, catch,
OverflowException.
catch FormatException
OverflowException, catch
OverflowException. , ,
, .
, C# Microsoft .NET
Framework, . .NET Framework
,
. -
, ,
, ,
! -
?
-
. , -
. ( 12 .)
FormatException OverflowException, ,
174 6
SystemException. SystemException
, Exception
. Exception, -
.
Exception ,
.NET Framework. , -
, , .
, -
:
try
{
int leftHandSide = int.Parse(lhsOperand.Text);
int rightHandSide = int.Parse(rhsOperand.Text);
int answer = doCalculation(leftHandSide, rightHandSide);
result.Text = answer.ToString();
}
catch (Exception ex) //
{
//...
}
Exception, -
,
:
catch
{
// ...
}
. ,
,
, -
catch .
, , -
: ,
, try? FormatException
Exception ,
( )?
, -
, ,
. , Exception
FormatException FormatException -
. try
175
.
,
.
C#,
. -
,
. ,
when. :
catch (Exception ex) when (ex.GetType() != typeof(System.OutOfMemoryException))
{
// , ,
// OutOfMemoryException
}
( Exception),
, (out-
of-memory), . ( GetType
, .)
, ,
. ,
, ,
, .
, ,
, try catch
.
-
.
. Left Operand ,
. -
.
176 6
try catch
Visual Studio 2015. -
. , Left Operand John,
Right Operand 2. + Addition, Calculate.
, -
, ,
Visual Studio .
Visual Studio , -
.
, : Input string was not in a
correct format. ( -
) (.6.2).
, addValues -
int.Parse. ,
John .
(View
Detail). , -
. System.
FormatException, (.6.3).
,
. , Visual Studio,
, ,
.
, InnerException
. -
, , ,
InnerException null (. .6.3). ,
, , , , -
.
177
. 6.2
. 6.3
OK,
Visual Studio .
MainPage.xaml.cs addValues.
try (
), ,
FormatException:
178 6
try
{
int lhs = int.Parse(lhsOperand.Text);
int rhs = int.Parse(rhsOperand.Text);
int outcome = 0;
FormatException, -
, Message
, .
.
Left Operand John, Right
Operand 2. + Addition, Calculate.
FormatException,
Result Input string was not in a
correct format. .
John 10. Right Operand Sharp,
Calculate.
try , , -
, -
.
Right Operand Sharp 20 ,
+Addition, Calculate. , -
, Result 30.
Left Operand 10 John, Subtraction,
Calculate.
Visual Studio -
FormatException.
subtractValues,
try-catch.
.
179
. 6.4
try catch addValues -
,
: subtractValues, multiplyValues, divideValues remainderValues.
, -
, .
calculateClick ,
Calculate. , -
,
calculateClick. subtractValues, multiplyValues, divideValues
remainderValues FormatException,
calculateClick ,
, -
.
180 6
MainPage.xaml.cs addValues.
try , -
:
private void addValues()
{
int leftHandSide = int.Parse(lhsOperand.Text);
int rightHandSide = int.Parse(rhsOperand.Text);
int outcome = 0;
calculateClick. try
, :
private void calculateClick(object sender, RoutedEventArgs e)
{
try
{
if ((bool)addition.IsChecked)
{
addValues();
}
else if ((bool)subtraction.IsChecked)
{
subtractValues();
}
else if ((bool)multiplication.IsChecked)
{
multiplyValues();
}
else if ((bool)division.IsChecked)
{
divideValues();
}
else if ((bool)remainder.IsChecked)
{
remainderValues();
}
}
catch (FormatException fEx)
{
result.Text = fEx.Message;
}
}
.
181
, -
FormatException Result
Input string was not in a correct format. ,
addValues,
calculateClick.
-Subtraction, Calculate. -
subtractValues,
calculateClick , .
, *Multiplication, /Division %Remainder,
, FormatException -
.
Visual Studio .
, -
, .
,
. -
, , ,
.
2
, + *, , int
double. , -
. , C# int 32. int
, ,
: 2147483648 2147483647.
int, int.MinValue int.MaxValue.
int- . ,
, int-,
2147483647? . -
C# , , -
. (
182 6
,
2147483648.) -
:
,
-
. ,
( !), int- .
, .
-
, -
, , ,
checked unchecked.
, .
checked
checked , -
checked. ,
, ,
checked, OverflowException:
, checked. ,
checked , -
, .
, ,
unchecked.
183
unchecked Overflow
Exception, :
checked unchecked
,
, , ,
checked unchecked:
int wontThrow = unchecked(int.MaxValue + 1);
int willThrow = checked(int.MaxValue + 1);
(+= =),
(++) (--) ,
checked unchecked. ,
x += y , x = x + y.
checked unchecked
( ) .
, ,
int long.
OverflowException, 0,0. (, 2
, .NET Framework
.)
, -
Visual Studio 2015.
Visual Studio 2015 .
.
Left Operand 9876543, Right Operand 9876543.
* Multiplication, Calculate. Result -
1195595903. .
,
32- , int.
184 6
Visual Studio .
MainPage.xaml.cs
multiplyValues, :
OverflowException,
.
. Left Operand
9876543, Right Operand 9876543. *Multiplication,
Calculate. Visual Studio -
, OverflowException.
.
. , -
MainPage.xaml.cs, calculateClick.
( )
FormatException:
result.Text = oEx.Message;
}
}
, -
FormatException. Exception
,
-.
,
. Left Operand 9876543, Right
Operand 9876543. * Multiplication, Calculate.
OverflowException -
Result Arithmetic operation resulted in an overflow
( ).
Visual Studio .
VISUAL STUDIO
Visual Studio -
, , , -
.
,
.
. ,
.
(.6.5).
. 6.5
186 6
. 6.6
, monthName,
int- . ,
monthName(1) January, monthName(2) February ..
, ,
1 12? ,
, . .NET
Framework , -
. ,
.
( , , -
, C#.)
.NET Framework
187
ArgumentOutOfRangeException. , -
, throw:
public static string monthName(int month)
{
switch (month)
{
case 1 :
return "January";
case 2 :
return "February";
...
case 12 :
return "December";
default :
throw new ArgumentOutOfRangeException("Bad month");
}
}
throw .
,
. ,
ArgumentOutOfRangeException. ,
Message . -
7
.
MathsOperators,
, -
.
,
-
, -
.
Visual Studio 2015 . -
Left Operand 24, Right Operand 36,
Calculate.
Expression Result . ,
, .
Result .
Visual Studio . , -
MainPage.xaml.cs, calculateClick,
:
188 6
, , , -
.
IsChecked, ,
. IsChecked
, true, ,
false, . (
8 .)
if , -
, . (
,
.) ,
if- true
.
if-else
else
189
result,
.
if-else else -
InvalidOperationException.
:
if ((bool)addition.IsChecked)
{
addValues();
}
...
else if ((bool)remainder.IsChecked)
{
remainderValues();
}
else
{
throw new InvalidOperationException("No operator selected");
}
, MainPage.xaml.cs,
calculateClick, ,
, :
...
catch (FormatException fEx)
{
result.Text = fEx.Message;
}
catch (OverflowException oEx)
{
result.Text = oEx.Message;
}
190 6
InvalidOperationException, -
,
.
. Left Operand
24, Right Operand 36, Calculate.
Result No operator selected (
).
Visual Studio, , ,
Visual Studio
(common language runtime) , -
. .
, Visual
Studio CLR- !
Visual Studio .
. -
, -
. ,
,
DivideByZeroException. (
.)
calculateClick .
-
,
Exception. ,
-
.
Exception
. ,
-
. Exception -
. -
, .
,
, DivideByZero
Exception .
finally 191
, MainPage.xaml.cs,
calculateClick
:
catch (Exception ex)
{
result.Text = ex.Message;
}
.
. -
, ,
, ,
.
Left Operand 24, Right Operand 36,
Calculate. , Result -
No operator selected.
InvalidOperationException.
Left Operand John, + Addition,
Calculate. , Result -
Input string was not in a correct format.
FormatException.
Left Operand 24, Right Operand 0.
/ Division, Calculate. , Result
Attempted to divide by zero. -
Exception.
,
, ,
. , Visual
Studio .
finally
, -
. , , - -
,
. ,
192 6
, , ,
, .
, 5 -
. -
, reader.Dispose
while, :
TextReader reader = ...;
...
string line = reader.ReadLine();
while (line != null)
{
...
line = reader.ReadLine();
}
reader.Dispose();
-
,
. , -
,
. :
, ( ),
, -
reader.Dispose. ,
.
, -
.
,
,
finally. try
, try.
try, finally, , -
finally, ,
. ,
, finally.
( ,
, ),
finally. , finally -
.
193
reader.Dispose
:
TextReader reader = ...;
...
try
{
string line = reader.ReadLine();
while (line != null)
{
...
line = reader.ReadLine();
}
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
, finally -
reader.Dispose.
14
.
, try catch -
. ,
checked unchecked
.
,
finally.
,
Visual Studio 2015 7.
Visual Studio 2015,
.
, .
194 6
, -
, :
try
{
...
}
catch (FormatException fEx)
{
...
}
checked, :
- int number = Int32.MaxValue;
checked
{
number++;
}
throw, :
throw new FormatException(source);
- ,
- Exception, :
try
{
...
}
catch (Exception ex)
{
...
}
- finally, :
- try
, {
...
}
finally
{
//
}
II
C#
I , , -
, -
, . ,
. ,
II. ,
, ,
, C#. ,
, C# -
(common language
runtime (CLR)) . ,
,
.
7
, :
, -
;
public private;
new
;
;
static , -
;
.
Windows, Microsoft .NET Framework -
. , Console Exception,
.
, .
, , - -
, .
,
, ,
, ,
. , ,
, , ,
.
197
.
, -
. ,
. ,
( , , ..)
( , .). -
,
. ,
,
. ,
.
, -
, ,
, ,
. -
, Microsoft Visual C#.
, -
. , ,
, , ,
, .
,
. , -
Console.WriteLine, ,
Console , .
, ,
, .
, .
. :
, -
;
, -
.
198 7
C# class.
.
Circle,
( ) (
):
class Circle
{
int radius;
double Area()
{
return Math.PI * radius * radius;
}
}
Math
. Math.PI -
3,14159265358979, .
(, Area) (,
radius). , .
, 2 ,
, , 3
,
.
Circle , ,
. ,
Circle, -
, :
Circle c; // Circle-
c = new Circle(); //
new.
, int float, -
:
int i;
i = 42;
.
, C#
. :
199
Circle c;
c = 42;
, Circle- 42?
, ,
. 8 -
. ,
new , .
-
:
Circle c;
c = new Circle();
Circle d;
d = c;
, 8, ,
.
. -
. ,
.
.
, Circle .
, ,
. (,
radius) (, Area)
, ,
. , ,
Circle, radius -
Area, !
public private,
.
(private),
. , -
private. ,
,
.
200 7
(public),
, . -
, public.
Circle. Area , radius
:
class Circle
{
private int radius;
C++, ,
public private .
.
radius , , -
Circle. Area
Circle, , Area radius.
,
radius. , -
.
, , ,
. -
, false null.
.
, -
.
.
.
, C#
.
-
. , Area A ( ), -
. PascalCase,
Pascal.
201
( )
. , radius
r ( R), .
(camelCase).
camelCase
,
, , ,
_radius. -
, .
: -
,
.
,
. , -
, ,
(, Microsoft Visual Basic),
.
new , -
, .
, ,
, -
.
,
. , ,
, ( void). -
. ,
. ( -
.) ,
, .
, ,
, . Circle
, radius 0:
class Circle
{
private int radius;
202 7
public Circle() //
{
radius = 0;
}
public double Area()
{
return Math.PI * radius * radius;
}
}
, C#, -
, . , ,
, .
( ),
.
(public). -
, ,
. (private),
, Circle
, Circle.
, .
, .
Circle Area.
, Area
Circle-:
Circle c;
c = new Circle();
double areaOfCircle = c.Area();
. ,
Circle, Circle-,
Area. , .
Circle- , -
radius
. radius ,
.
, , ,
. , Console.
WriteLine, ,
.
203
Circle , -
:
class Circle
{
private int radius;
public Circle() //
{
radius = 0;
}
, .
-
Circle:
Circle c;
c = new Circle(45);
,
, , new. -
, ,
, int-.
C#:
, .
,
, , -
.
,
.
x- y- -
.
new .
204 7
, ,
, . , -
, .
C#, -
, -
, .
Visual Studio 2015 ,
Windows (Universal Windows Platform (UWP)), ,
, , -
, Visual Studio
.
-
partial. , Circle
circ1.cs ( )
circ2.cs ( ), circ1.cs -
:
partial class Circle
{
public Circle() //
{
this.radius = 0;
}
circ2.cs :
partial class Circle
{
private int radius;
, ,
.
205
Visual Studio 2015 Classes,
\Microsoft Press\VCSBS\Chapter 7\Classes .
Program.cs,
. Program Main.
doWork, try, -
. try-catch, ,
Main, , doWork,
, .
doWork , // TODO:.
TODO -
,
. ,
, , // TODO: doWork. Visual Studio
,
, .
, .
(.7.1).
TODO. ,
, ,
.
. 7.1
206 7
Point.cs.
Point, -
,
x y. Point ,
//TODO:.
Program.cs. Program
doWork, // TODO: :
Point -
.
(Build) (Build Solution).
,
Point. C#
, -
.
Point, Point.cs. -
// TODO: , int-
x y, Console.WriteLine
.
:
class Point
{
public Point(int x, int y)
{
Console.WriteLine($"x:{x}, y:{y}");
}
}
.
: ,
"x" "Point.Point(int, int)".
,
doWork ,
.
Point, . -
,
.
Point , ,
Console.WriteLine
207
class Point
{
public Point()
{
Console.WriteLine("Default constructor called");
}
.
.
Program.cs doWork.
bottomRight Point Point,
.
.
1366 768 ,
1366768, .
doWork :
.
,
(.7.2).
, ,
Visual Studio 2015.
Point int- -
x y -
. Point.cs Point,
int- x y.
. Point
:
208 7
class Point
{
private int x, y;
public Point()
{
Console.WriteLine("default constructor called");
}
. 7.2
Point -
x y x y.
. ,
:
public Point(int x, int y) // !
{
x = x;
y = y;
}
, -
. x=x;
, x ,
? : !
209
, , .
, ,
, . ,
, .
this,
, , .
this .
Point, ,
Console.WriteLine ,
:
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
Point x y
1. .
, ,
this :
public Point()
{
this.x = -1;
this.y = -1;
}
. ,
. ( ,
.)
, , -
,
. ( .)
Point,
DistanceTo .
Visual Studio 2015 Point Classes -
DistanceTo. Point- other -
, double.
210 7
DistanceTo :
class Point
{
...
public double DistanceTo(Point other)
{
}
}
DistanceTo -
Point, , Point,
.
x y.
DistanceTo int- xDiff -
this.x other.x.
, , :
public double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
}
int- yDiff -
this.y other.y.
:
public double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
}
x y ,
. ,
(private) , : -
, , -
, , ,
.
-
xDiff yDiff. Sqrt,
,
System.Math.
distance, double, -
:
211
DistanceTo return
distance:
public double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
return distance;
}
DistanceTo.
doWork Program. ,
Point- origin bottomRight, distance
double. double- ,
DistanceTo, origin
bottomRight.
doWork :
static void doWork()
{
Point origin = new Point();
Point bottomRight = new Point(1366, 768);
double distance = origin.DistanceTo(bottomRight);
}
origin ,
Microsoft IntelliSense DistanceTo.
doWork , -
distance Console.WriteLine.
doWork :
static void doWork()
{
Point origin = new Point();
Point bottomRight = new Point(1366, 768);
double distance = origin.DistanceTo(bottomRight);
Console.WriteLine($"Distance is: {distance}");
}
.
212 7
, 1568,45465347265,
, Visual
Studio2015.
Sqrt,
Math. , Circle, Math -
PI. , Sqrt
PI .
, Math. ,
, Point.DistanceTo
origin.DistanceTo. - ?
,
, , -
,
- .
WriteLine Console,
. Sqrt. Sqrt
Math, Math
Sqrt :
Math m = new Math();
double d = m.Sqrt(42.24);
. Math
. , Sqrt,
,
.
, Sqrt -
.
C# .
,
.
Sqrt Math:
213
class Math
{
public static double Sqrt(double d)
{
...
}
...
}
Sqrt :
double d = Math.Sqrt(42.24);
- -
, ,
static.
, ,
. ( -
.)
Circle NumCircles Circle
Circle :
class Circle
{
private int radius;
public static int NumCircles = 0;
public Circle() //
{
radius = 0;
NumCircles++;
}
Circle -
NumCircles, NumCircles++;
. ,
214 7
NumCircles this,
NumCircles .
, NumCircles
, Circle-, Circle:
Console.WriteLine($"Number of Circle objects: {Circle.NumCircles}");
,
.
( ).
const
, const, -
,
. const constant
. static const-,
. ,
, const ,
(, int double),
. ( 9
.)
, , const Math PI:
class Math
{
...
public const double PI = 3.14159265358979;
}
C# -
. .
( , ,
.)
. -
, -
new .
new , .
215
( .) -
,
, , ,
static. ,
.
Math,
, :
public static class Math
{
public static double Sin(double x) {...}
public static double Cos(double x) {...}
public static double Sqrt(double x) {...}
...
}
Math ,
- .
, , Math.
Sqrt Console.WriteLine.
(using)
.
, using, -
. :
using static System.Math;
using static System.Console;
...
var root = Sqrt(99.9);
WriteLine($"The square root of 99.9 is {root}");
using
static. System.Math System.
Console ( -
).
Sqrt WriteLine. ,
.
. ,
, ,
- , ,
, . -
216 7
Visual Studio 2015 Point.
int-
objectCount
:
class Point
{
...
private static int objectCount = 0;
...
}
, objectCount, private
static .
private, static.
Point-
objectCount (
). Point :
class Point
{
private int x, y;
private static int objectCount = 0;
public Point()
{
this.x = -1;
this.y = -1;
objectCount++;
}
217
.
objectCount , -
, objectCount
. , objectCount
. objectCount
,
objectCount 1.
: Point
Point-? objectCount
, .
objectCount ,
objectCount,
. -
, objectCount.
.
Point ObjectCount,
int-, .
, , -
objectCount:
class Point
{
...
public static int ObjectCount() => objectCount;
}
Program. doWork -
, ObjectCount
Point ( ):
218 7
ObjectCount Point, ,
Point-, origin bottomRight.
ObjectCount Point-,
2.
. ,
Number of Point objects: 2 ( ,
distance). ,
Visual Studio 2015.
, . , , -
, ,
, .
( 20 -
.)
.
new
,
:
Name,
John, Age, 47.
, -
.
,
, , . ,
, : , -
?
219
myAnonymousObject? : , -
!
var myAnonymousObject
, -
, :
, var -
, .
,
.
,
:
,
, :
, -
, C# ,
. myAnonymousObject anotherAnonymousObject
,
, ,
. ,
:
anotherAnonymousObject = myAnonymousObject;
, -
, . -
8.
-
. , ,
, ,
- .
,
.
220 7
, . ,
, ,
,
public. ,
new , -
. , ,
,
.
,
Visual Studio 2015 8.
Visual Studio 2015,
. -
, .
class, -
,
. -
, :
class Point
{
...
}
, ,
( void) , :
class Point
{
public Point(int x, int y)
{
...
}
}
new
, :
Point origin = new Point(0, 0);
221
- static, -
:
class Point
{
public static int ObjectCount()
{
...
}
}
- , , -
, :
int pointsCreatedSoFar = Point.ObjectCount();
- static , :
class Point
{
...
private static int objectCount;
}
const
const static, :
class Math
{
...
public const double PI = ...;
}
, , -
, :
double area = Math.PI * radius * radius;
8
, :
;
ref out;
, (boxing);
,
(unboxing) (casting).
7 ,
new. ,
. , -
, int, double char, -
.
, (, 42) int-, -
, .
, Circle, 7,
-. Circle-,
, ,
Circle, , -
( ),
Circle- (,
). Circle- ,
new.
. .
C#,
Microsoft .NET Framework, ,
.
string C# . ,
(
)
. , , -
, string. string C#
System.String.
i int
42.
copyi int, i copyi,
copyi , i (42).
copyi i , 42
: i, copyi.
i, copyi . ,
:
int i = 42; // i
int copyi = i; /* copyi , i:
i, copyi 42 */
i++; /* i copyi;
i 43, copyi - 42 */
, c ,
Circle, . c Circle- c
Circle-; , c,
Circle- .
refc ( Circle-)
c, refc , c.
224 8
, Circle-
, refc, c.
:
Circle c = new Circle(42);
Circle refc = c;
. 8.1
. , , -
, :
.
.
Circle- c Circle-
refc, ,
refc Circle,
c refc, :
Circle refc = new Circle();
refc.radius = c.radius; //
- Circle (,
radius), .
,
225
,
c refc. , 15
.
, Clone,
, .
Clone
. ,
Clone Circle :
class Circle
{
private int radius;
//
...
public Circle Clone()
{
// Circle-
Circle clone = new Circle();
//
clone.radius = this.radius;
// Circle-,
return clone;
}
}
,
, -
(, Circle ,
Point- 7, Circle
),
Clone, Clone Circle
.
. , Clone ,
.
:
? , private
. ,
- .
, ,
. ,
: , Clone, .
clone.radius = this.radius; ,
radius clone Circle. -
, (private) ,
. private static. -
(private), .
(static), -
.
226 8
- -
Microsoft Visual Studio 2015 Parameters,
\Microsoft Press\VCSBS\Chapter 8\Parameters .
C#: Pass.cs, Program.cs WrappedInt.cs.
Pass.cs. Pass,
, // TODO:.
,
TODO .
// TODO: Pass
Value. int- (
) param void. Value,
, -
42 param:
namespace Parameters
{
class Pass
{
public static void Value(int param)
{
param = 42;
}
}
}
, -
static. Value
Pass Pass-. -
, , -
.
Program.cs, doWork
Program. doWork Main, -
. 7, try,
.
doWork , -
.
int- i
.
i Console.
WriteLine.
227
Pass.Value i .
i .
Console.WriteLine Pass.Value
, Pass.Value i.
doWork :
static void doWork()
{
int i = 0;
Console.WriteLine(i);
Pass.Value(i);
Console.WriteLine(i);
}
,
. , 0 .
Pass.Value,
42, -
, i .
.
, , int-, -
.
WrappedInt.cs. WrappedInt,
, // TODO:.
WrappedInt
Number, int:
namespace Parameters
{
class WrappedInt
{
public int Number;
}
}
Pass.cs. Pass -
Reference.
WrappedInt- param void.
Reference 42 param.Number:
public static void Reference(WrappedInt param)
{
param.Number = 42;
}
228 8
Program.cs.
doWork ,
.
WrappedInt- wi -
WrappedInt- .
wi.Number .
Pass.Reference wi .
wi.Number .
, Console.WriteLine , -
wi.Number Pass.Reference. doWork
( ):
static void doWork()
{
// int i = 0;
// Console.WriteLine(i);
// Pass.Value(i);
// Console.WriteLine(i);
,
. , ,
wi.Number Pass.Reference.
, 0 42.
, Visual Stu
dio2015.
, .
wi.Number ,
, . wi
WrappedInt-, int-.
wi Pass.Reference.
WrappedInt ( ), wi param -
WrappedInt-. , -
param Pass.Reference,
wi, .
, , WrappedInt-
Pass.Reference (.8.2).
, 229
. 8.2
,
, .
:
int i = 0;
double d = 0.0;
, , ,
:
Circle c = new Circle(42);
, , ?
,
- .
Circle-, -
Circle:
Circle c = new Circle(42);
Circle copy = new Circle(99); //
...
copy = c; // copy c
Circle- radius,
99, copy ,
copy c?
. -
, , ,
14
230 8
. , -
,
,
.
, -
, -
. ,
. ,
, ,
, , ,
:
Circle c = new Circle(42);
Circle copy; // !!!
...
if (copy == // copy
// , ,
// ?
{
copy = c; // copy c
...
}
if copy ,
,
? : ,
(null-).
C# null .
null , .
:
Circle c = new Circle(42);
Circle copy = null; //
...
if (copy == null)
{
copy = c; // copy c
...
}
NULL-
C# null-
, . -
,
(?).
, 231
, , Area
Circle-, null:
Circle c = null;
Console.WriteLine($"The area of circle c is {c.Area()}");
Circle.Area NullReferenceException,
, .
, Circle.Area
Circle- null:
if (c != null)
{
Console.WriteLine($"The area of circle c is {c.Area()}");
}
, c null,
. Circle.Area
Circle-
null-:
Console.WriteLine($"The area of circle c is {c?.Area()}");
-
, , ,
null. :
The area of circle c is
,
. null- -
,
, null-.
,
.
, null
, . -
C# :
int i = null; //
C# ,
,
. , ,
, ,
null. ,
, (?):
int? i = null; //
232 8
, , , null,
-
:
if (i == null)
...
-
, .
:
int? i = null;
int j = 99;
i = 100; // ,
i = j; // ,
, . ,
,
. i j
, :
j = i; //
, , i null-
, j ,
. , , ,
, , -
. , Pass.Value
int-,
:
int? i = 99;
Pass.Value(i); //
,
, null-. , -
, ,
null- .
, , ,
, . HasValue ,
ref out 233
, , , -
. , , -
, Value:
int? i = null;
...
if (!i.HasValue)
{
// i , 99
i = 99;
}
else
{
// ,
Console.WriteLine(i.Value);
}
4 ,
(!) .
i, , -
, ( ),
99,
. HasValue
-
. , Value
. -
, int? , -
. HasValue Value
, , ,
,
. 9
.
Value , ,
. -
, . ,
, .
ref out
, , -
. ,
(, int),
(, int?), (-
, WrappedInt). ,
234 8
. ,
, , 42, 43. doIncrement
(arg), :
static void doIncrement(int param)
{
param++;
}
static void Main()
{
int arg = 42;
doIncrement(arg);
Console.WriteLine(arg); // 42, 43
}
,
,
, -
. : ,
, , , , -
- .
, , -
, (,
, ). -
.
, . C#
ref out.
ref-
ref, C#
, , .
ref- , , -
, .
ref-
ref.
, .
,
ref:
static void doIncrement(ref int param) // ref
{
param++;
}
static void Main()
ref out 235
{
int arg = 42;
doIncrement(ref arg); // ref
Console.WriteLine(arg); // 43
}
doIncrement ,
, , , -
. -
43.
, C# ,
, .
:
, ,
ref-. ,
arg ,
. , param++;
doIncrement
arg++;, , arg -
:
static void doIncrement(ref int param)
{
param++;
}
out-
, ref- -
. ,
.
out.
ref. out
, .
ref, , , -
. out-,
out.
236 8
, doInitialize
param :
static void doInitialize(out int param)
{
//
}
out- - ,
. , -
doInitialize arg,
:
static void doInitialize(out int param)
{
param = 42;
}
static void Main()
{
int arg; //
doInitialize(out arg); //
Console.WriteLine(arg); // 42
}
ref- .
ref-
Visual Studio 2015 Parameters.
Pass.cs Value, ref-
.
Value :
class Pass
{
public static void Value(ref int param)
{
param = 42;
}
...
}
237
Program.cs.
. , -
doWork Pass.Value(i); . ,
Value ref-. ,
Pass.Value ref-.
, WrappedInt,
.
doWork :
class Program
{
static void doWork()
{
int i = 0;
Console.WriteLine(i);
Pass.Value(ref i);
Console.WriteLine(i);
...
}
}
,
. ,
, 0 42. , Pass.
Value i.
, Visual Stu
dio2015.
ref out
.
.
-
. ,
,
.
, C#,
, , -
, -.
238 8
().
.
,
, . -
( , - -
), , ,
.
:
, .
, -
,
. i
while , while ,
:
while (...)
{
int i = ; // i
...
}
// i
new ( ),
, , -
(). ,
.
, , ,
(, , ).
14. ,
, -
: new,
.
.
() (
). , , -
, .
-
.
,
. , -
.
239
, ,
. ,
, .
,
, . ,
, .
.
.
. (,
.) -
, ,
.
, Method:
void Method(int param)
{
Circle c;
c = new Circle(param);
...
}
, , param , 42.
,
int-, 42. -
, ,
( ),
. Circle-
c. , -
Circle.
new.
Circle Circle-.
Circle c.
.8.3.
.
, ( c)
.
() . ,
new OutOfMemoryException
.
240 8
. 8.3
Circle- . -
, , Circle, -
(null).
,
. , c param,
.
, Circle , - -
(.14).
System.Object
.NET Framework
Object, System.
System.Object, ,
, 12 .
,
System.Object System.Object
, . System.
Object , C# -
object. object,
System.Object .
object , System.
Object.
, (, string System.String
, 9).
c o -
Circle. , c Circle, o object
241
( System.Object),
:
Circle c;
c = new Circle(42);
object o;
o = c;
(.8.4) , c o
().
. 8.4
, object
. object
. ,
i ( int, ) 42,
o ( object, -
) i:
int i = 42;
object o = i;
, , -
. , i ,
. o
i, . -
:
, , .
,
242 8
i, object o .
(boxing). (.8.5).
. 8.5
i, -
, o, -
. , ,
.
object
, , -
.
int-,
o, :
int i = o;
. ,
inti=o; . o -
, int-. ,
, :
Circle c = new Circle();
int i = 42;
object o;
o = c; // o circle-
i = o; // i?
243
,
(cast). ,
. object
:
int i = 42;
object o = i; //
i = (int)o; //
. -
, int. , ,
o .
. , o int,
, .
o int- ,
int- i. (
i.) . -
(.8.6).
. 8.6
, o int-,
, .
-
InvalidCastException.
:
Circle c = new Circle(42);
object o = c; // , Circle
nt i = (int)o; // ,
//
.8.7.
244 8
InvalidCastExeption
. 8.7
.
, ,
. , ,
,
. -
17 .
, , , , ,
, -
.
. C# ,
, .
, ,
, InvalidCastException.
.
,
, .
C# , is as, -
.
245
is
is
:
WrappedInt wi = new WrappedInt();
...
object o = wi;
if (o is WrappedInt)
{
WrappedInt temp = (WrappedInt)o; // ; o WrappedInt
...
}
: ,
, , .
, , -
, true, false.
, o, ,
, .
as
as , is, .
:
WrappedInt wi = new WrappedInt();
...
object o = wi;
WrappedInt temp = o as WrappedInt;
if (temp != null)
{
... //
}
is, as , -
.
. , ,
WrappedInt- temp. -
, null temp
.
is as, ,
12.
246 8
, C C++.
.
C C++,
, , ,
, -
. .
,
( , ). -
.
, pi
:
int *pi;
pi , -
. , pi
i,
, address-of, (&), -
:
int *pi;
int i = 99;
...
pi = &i;
pi
i :
*pi = 100;
i 100, pi
, i.
, ,
C C++, , . -
* (
),
, , & *.
, -
,
, . -
, ,
. ,
-
: ( Windows)
, ,
,
.
247
C# .
, C#,
.
, ,
unsafe:
public static void Main(string [] args)
{
int x = 99, y = 100;
unsafe
{
swap (&x, &y);
}
Console.WriteLine($"x is now {x}, y is now {y}");
}
public static unsafe void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
, ,
.
,
. ,
,
.
. ,
, . ,
, ,
, , ,
,
Windows.
, -
, 14.
,
, ,
.
ref out. , (,
int- 42) System.Object
248 8
, System.Object
. ,
(, int-)
System.Object ( )
System.Object , int-.
,
Visual Studio 2015 9.
Visual Studio 2015,
. -
, .
. -
,
, :
int i = 42;
int copyi = i;
. -
,
, :
Circle c = new Circle(42);
Circle refc = c;
, - -
- ? , :
int? i = null;
ref- ref.
,
. -
, -
, , :
static void Main()
{
int arg = 42;
doWork(ref arg);
Console.WriteLine(arg);
}
249
out- out.
,
. -
, -
, :
static void Main()
{
int arg;
doWork(out arg);
Console.WriteLine(arg);
}
object -
, :
object o = 42;
, ,
, :
int i = (int)o;
- is -
, :
WrappedInt wi = new WrappedInt();
...
object o = wi;
if (o is WrappedInt)
{
WrappedInt temp = (WrappedInt)o;
...
}
as
null-, -
:
WrappedInt wi = new WrappedInt();
...
object o = wi;
WrappedInt temp = o as WrappedInt;
if (temp != null)
...
9
, :
;
;
;
;
.
8
, Microsoft Visual C#:
. , -
, ,
(). 7
,
.
.
C# : .
.
, . -
, , 0, 1,
2 3 . ,
251
. 0,
, -
. . -
, season,
0,
1, 2 3. C# .
( enum-),
.
enum, -
,
.
Season,
Spring, Summer, Fall Winter:
,
. Season, , -
, Season, Season
Season:
class Example
{
public void Method(Season parameter) //
{
Season localVariable; //
...
}
private Season currentSeason; //
}
-
, . ,
, :
,
(?), -
, .
null , , -
:
Season? colorful = null;
Season.Fall, Fall.
,
.
,
Console.WriteLine , -
, . -
, , -
ToString, :
string name = colorful.ToString();
Console.WriteLine(name); // 'Fall'
( -
, 16
) , -
. ,
-
(==),
,
!
.
.
.
. 8 ,
, - . -
Fall, 2 (,
Season- Spring 0, Summer 1, Fall 2 Winter 3):
253
(, Spring)
(, 1):
enum Season { Spring = 1, Summer, Fall, Winter }
, -
, (, 1).
-
,
,
, 0.
Spring,
Summer, Fall Winter 1, 2, 3 4.
. , fall ()
autumn.
:
enum Season { Spring, Summer, Fall, Autumn = Fall, Winter }
int. -
. , Season int,
short, :
enum Season : short { Spring, Summer, Fall, Winter }
short : int -
, short,
, int,
.
-
: byte, sbyte, short, ushort, int, uint, long ulong.
. , byte,
256 ( ).
254 9
, ,
.
, -
, .
Microsoft Visual Studio 2015 StructsAndEnums,
\Microsoft Press\VCSBS\Chapter 9\StructsAndEnums -
.
Month.cs. ,
StructsAndEnums // TODO:.
// TODO: -
Month,
StructsAndEnums. .
12 Month January
December.
namespace StructsAndEnums
{
enum Month
{
January, February, March, April,
May, June, July, August,
September, October, November, December
}
}
Program.cs. Main,
, doWork
.
doWork ,
Month- first, Month.
January. first
. doWork :
static void doWork()
{
Month first = Month.January;
Console.WriteLine(first);
}
Month , Microsoft
IntelliSense , Month.
255
-
. Visual Studio 2015
.
December, -
12 (.9.1).
-
, . 9.1
256 9
,
, , , -
.
, -
Visual Studio 2015.
8 , ,
.
,
.
. .
, , ,
.
, ,
( , ) .
,
. C# , int, long float, -
System.Int32, System.Int64 System.Single -
. , -
. ,
ToString,
. C#
:
int i = 55;
Console.WriteLine(i.ToString());
Console.WriteLine(55.ToString());
float f = 98.765F;
Console.WriteLine(f.ToString());
Console.WriteLine(98.765F.ToString());
ToString , -
Console.WriteLine .
.
, int.Parse,
. -
Parse Int32:
string s = "42";
int i = int.Parse(s); // , Int32.Parse
257
. ,
Int32.MaxValue ,
int-, Int32.MinValue -
.
, C#, -
Microsoft .NET Framework.
, string object ( ),
.
bool System.Boolean
byte System.Byte
decimal System.Decimal
double System.Double
float System.Single
int System.Int32
long System.Int64
object System.Object
sbyte System.SByte
short System.Int16
string System.String
uint System.UInt32
ulong System.UInt64
ushort System.UInt16
struct,
. . , -
, Time, int-
hours, minutes seconds:
258 9
struct Time
{
public int hours, minutes, seconds;
}
, -
, ,
, . , minutes seconds
, 60, .
:
struct Time
{
private int hours, minutes, seconds;
...
public Time(int hh, int mm, int ss)
{
this.hours = hh % 24;
this.minutes = mm % 60;
this.seconds = ss % 60;
}
. , ,
, (==) -
(!=).
Equals(), ,
-
. 21 ,
, .
.
-
. ,
, ,
,
. ,
.
,
,
.
259
,
. .
(
). , Time
, , Time :
struct Time
{
public Time() { ... } //
...
}
,
, ,
.
, . -
0, false null. , .
, ,
,
.
.
,
.
-
. ,
. ,
, ,
, Time
, :
struct Time
{
private int hours, minutes, seconds;
...
public Time(int hh, int mm)
{
this.hours = hh;
this.minutes = mm;
} // : seconds
}
260 9
,
. .
, Time , -
, Time :
struct Time
{
private int hours = 0; //
private int minutes;
private int seconds;
...
}
.9.1.
9.1
- -
?
, -
?
- -
-
?
,
?
, -
?
-
?
, .
12 .
, . ,
Time, , Time:
261
struct Time
{
private int hours, minutes, seconds;
...
}
class Example
{
private Time currentTime;
, -
, , -
(?).
.
Time? currentTime = null;
,
. -
, -
:
Time now = new Time();
.9.2.
. 9.2
,
, :
Time now;
262 9
, -
. .9.3 now.
.
. 9.3
, now .
,
. -
, ,
, :
struct Time
{
private int hours, minutes, seconds;
...
public Time(int hh, int mm)
{
hours = hh;
minutes = mm;
seconds = 0;
}
}
now ,
:
Time now = new Time(12, 30);
.9.4.
.
.
263
. 9.4
Date.cs, StructsAndEnums.
TODO Date, -
StructsAndEnums.
: int
year, Month month ( -
) int day.
Date :
struct Date
{
private int year;
private Month month;
private int day;
}
,
Date. year 0, month 0
( January) day 0. -
0 year , ,
day, .
year day
Date, year Y,
Y + 1900 (, ,
), day D, D + 1.
,
1 1900 .
, ,
264 9
year day .
,
,
.
,
,
, ,
.
Date .
: int- ccyy year, Month-
mm int- dd . -
. year
Y Y + 1900,
year ccyy 1900. day D D + 1,
, day dd 1.
Date (
):
struct Date
{
private int year;
private Month month;
private int day;
Date ToString.
, .
, year year + 1900,
day day + 1.
ToString :
struct Date
{
...
public override string ToString()
{
string data = $"{this.month} {this.day + 1} {this.year + 1900}";
return data;
}
}
265
ToString ,
. , ,
, ToString. -
, , ,
. ,
. ,
ToString, Date,
StructsAndEnums.Date. , -
, , -
, . override
, . -
12.
,
month, this.day + 1 this.year
+ 1900. ToString
.
Program.cs. doWork
. doWork ,
defaultDate, -
Date-,
Date-. doWork ,
defaultDate Console.
WriteLine.
Console.WriteLine
ToString.
doWork :
static void doWork()
{
...
Date defaultDate = new Date();
Console.WriteLine(defaultDate);
}
, -
. ,
January 1 1900.
doWork . -
weddingAnniversary
July 4 2015. (
, .)
weddingAnniversary.
doWork :
static void doWork()
{
...
Date weddingAnniversary = new Date(2015, Month.July, 4);
Console.WriteLine(weddingAnniversary);
}
, ,
July 4 2015. -
Visual Studio 2015.
,
, , ,
,
. ,
:
Date now = new Date(2012, Month.March, 19);
Date copy = now;
.9.5.
, now
:
Date now;
Date copy = now; // : now
,
, -
,
. ,
, -
. , , Time
, , now copy,
.
267
. 9.5
C++ ,
.
Date.cs, StructsAndEnums.
Date ,
. month December,
month January year :
struct Date
{
...
public void AdvanceMonth()
{
this.month++;
if (this.month == Month.December + 1)
{
this.month = Month.January;
this.year++;
}
}
}
Program.cs. doWork
,
defaultDate.
268 9
, ,
doWork. weddingAnniversary
weddingAnniversaryCopy :
-
doWork. AdvanceMonth
weddingAnniversary, weddingAnniversary
weddingAnniversaryCopy :
static void doWork()
{
...
weddingAnniversary.AdvanceMonth();
Console.WriteLine($"New value of weddingAnniversary is
{weddingAnniversary}");
Console.WriteLine($"Value of copy is still {weddingAnniversaryCopy}");
}
,
. , -
:
July 4 2015
Value of copy is July 4 2015
New value of weddingAnniversary is August 4 2015
Value of copy is still July 4 2015
weddingAnni
versary (July 4 2015).
weddingAnniversaryCopy. , ,
weddingAnniversary (July 4 2015). -
weddingAnniversary
(August 4 2015).
weddingAnniversaryCopy. ,
July 4 2015 .
Date ,
, . -
,
. -
.
269
,
. , -
:
July 4 2015
Value of copy is July 4 2015
New value of weddingAnniversary is August 4 2015
Value of copy is still August 4 2015
.
, weddingAnniversaryCopy
August 4 2015.
WINDOWS
C# -
(common language runtime (CLR)), .NET Framework.
CLR
(
Java, ).
C# C# , -
, (Common
Intermediate Language (CIL)). .
C# CLR CIL-
,
. -
, C# .
, .NET
Framework, Visual Basic F#.
Windows 7 -
, ,
Win32 API-,
Windows. ( , CLR
.NET Framework Win32 API,
.)
270 9
, -
. , , ,
.
, -
ToString.
271
,
Visual Studio 2015 10 .
Visual Studio 2015,
. -
, .
enum, ,
-
, :
enum Season { Spring, Summer, Fall, Winter }
, -
, , :
Season currentSeason;
- ,
, , :
currentSeason = Spring; //
currentSeason = Season.Spring; //
struct,
,
(, ), :
struct Time
{
public Time(int hh, int mm, int ss)
{ ... }
...
private int hours, minutes, seconds;
}
, ,
, :
Time now;
- , :
Time lunch = new Time(12, 30, 0);
10
, :
;
;
, ;
.
, -
.
( int, float,
Circle, Date ..). , ?
,
: ?
?
(, -
),
? ,
, .
? , , -
,
?
, , .
.
, ,
.
, ,
,
.
273
,
, .
, . , -
int- pins ( -
) :
int[] pins; //
. -
, . ,
Date-:
Date[] dates;
,
places ( Place), people (
Person) times ( Time).
.
, , -
(). (
, 8
.) , -
.
, int,
, .
, -
, new
. : -
, ,
.
, .
new, -
, ,
274 10
.
(0, null false ,
, ). -
,
pins, :
pins = new int[4];
.10.1 , ,
.
. 10.1
,
, -
, :
int size = int.Parse(Console.ReadLine());
int[] pins = new int[size];
0. , -
,
.
, .
-
, . ,
0,
null, DateTime
275
"01/01/0001 00:00:00". -
.
, . , -
pins int- 9,
3, 7 2, :
, ,
, , , ,
.
pins :
Random r = new Random();
int[] pins = new int[4]{ r.Next() % 10, r.Next() % 10,
r.Next() % 10, r.Next() % 10 };
System.Random -
. Next
0 Int32.MaxValue. Next ,
-
. Random ,
, ,
, -
. ,
. , -
.
:
int[] pins = new int[3]{ 9, 3, 7, 2 }; //
int[] pins = new int[4]{ 9, 3, 7 }; //
int[] pins = new int[4]{ 9, 3, 7, 2 }; //
, new-
.
:
int[] pins = { 9, 3, 7, 2 };
,
:
Time[] schedule = { new Time(12,30), new Time(5,30) };
276 10
-
, . , ,
, , pins int-,
double, string, struct
, int.
, C# -
:
var names = new[]{"John", "Diana", "James", "Francesca"};
C# , names
.
. -,
names var,
var[]. -,
new .
,
.
No best type found for implicitly-typed
array, ,
:
var bad = new[]{"John", "Diana", 99, 100};
,
- . -
double-, 3.5 99.999
double C# -
1 2 double-:
var numbers = new[]{1, 2, 3.5, 99.999};
, ,
.
, 7
.
, , -
:
var names = new[] { new { Name = "John", Age = 50 },
new { Name = "Diana", Age = 50 },
new { Name = "James", Age = 23 },
new { Name = "Francesca", Age = 21 } };
277
,
, .
, -
0, 1. 1 .
, 2 ( ) pins
int- :
int myPin;
myPin = pins[2];
, ,
:
myPin = 1645;
pins[2] = myPin;
.
, , -
, IndexOutOfRangeException:
try
{
int[] pins = { 9, 3, 7, 2 };
Console.WriteLine(pins[4]); // , 4-, ,
// 3
}
catch (IndexOutOfRangeException ex)
{
...
}
Microsoft .NET Framework
System.Array, -
. , ,
Length,
for. -
pins :
278 10
int[] pins = { 9, 3, 7, 2 };
for (int index = 0; index < pins.Length; index++)
{
int pin = pins[index];
Console.WriteLine(pin);
}
Length , ,
. 15 -
.
,
0,
Length 1. C# foreach,
,
. , ,
for, , foreach:
int[] pins = { 9, 3, 7, 2 };
foreach (int pin in pins)
{
Console.WriteLine(pin);
}
foreach (
int pin), .
. -
foreach -
:
, ,
for.
for .
foreach .
(, -
) (, ),
for.
foreach 0
Length 1.
- ,
for.
,
, for.
, -
for. , foreach
, .
279
-
foreach .
var -
C#
. ,
, , , -
. , -
, :
C# ,
.
, . ,
ProcessData, -
.
:
public void ProcessData(int[] data)
{
foreach (int i in data)
{
...
}
}
, ,
, ProcessData , ,
,
, ,
.
280 10
. . -
,
. , ,
:
public int[] ReadData()
{
Console.WriteLine("How many elements?");
string reply = Console.ReadLine();
int numElements = int.Parse(reply);
int[] data = new int[numElements];
for (int i = 0; i < numElements; i++)
{
Console.WriteLine($"Enter data for element {i}");
reply = Console.ReadLine();
int elementData = int.Parse(reply);
data[i] = elementData;
}
return data;
}
ReadData :
int[] data = ReadData();
MAIN
, , Main
:
static void Main(string[] args)
{
...
}
, Main
.
,
. Windows
(common language runtime (CLR)),
Main.
,
,
.
, .
MyFileUtil, -
.
ProcessFile ( ),
:
281
MyFileUtil
:
MyFileUtil C:\Temp\TestData.dat C:\Users\John\Documents\MyDoc.txt
. -
MyFileUtil.
(,
System.Array).
. ,
, ,
:
int[] pins = { 9, 3, 7, 2 };
int[] alias = pins; // alias pins
, pins[1],
alias[1].
( ),
, .
-, , -
, , . -, -
:
int[] pins = { 9, 3, 7, 2 };
int[] copy = new int[pins.Length];
for (int i = 0; i < pins.Length; i++)
{
copy[i] = pins[i];
}
,
Length .
,
, System.Array ,
282 10
. ,
CopyTo
. pins, -
, copy:
int[] pins = { 9, 3, 7, 2 };
int[] copy = new int[pins.Length];
pins.CopyTo(copy, 0);
-
System.Array Copy.
CopyTo, Copy
:
int[] pins = { 9, 3, 7, 2 };
int[] copy = new int[pins.Length];
Array.Copy(pins, copy, copy.Length);
Aray.Copy
length. ,
ArgumentOutOfRangeException. ,
, ArgumentException.
System.Array
Clone.
:
int[] pins = { 9, 3, 7, 2 };
int[] copy = (int[])pins.Clone();
Clone 8. Clone
Array object, Array, -
. , Clone, CopyTo Copy -
(
8). ,
Clone , , . -
.
, -
for.
, , ,
.
283
. , , -
, .
items, 24
. ,
, , -
:
int[,] items = new int[4, 6];
, -
, ( ),
.
items:
items[2, 3] = 99; // (2, 3) 99
items[2, 4] = items [2,3]; // (2, 3) (2, 4)
items[2, 4]++; // (2, 4)
-
.
cube. ,
:
int[, ,] cube = new int[5, 5, 5];
cube[1, 2, 1] = 101;
cube[1, 2, 2] = cube[1, 2, 1] * 3;
. .
cube 125 (5 5 5). , -
, 625 .
,
.
, -
, OutOfMemoryException.
C# -
. .
, , items,
40, 160 :
int[,] items = new int[4, 40];
284 10
,
.
,
.
, :
int[][] items = new int[4][];
int[] columnForRow0 = new int[3];
int[] columnForRow1 = new int[10];
int[] columnForRow2 = new int[40];
int[] columnForRow3 = new int[25];
items[0] = columnForRow0;
items[1] = columnForRow1;
items[2] = columnForRow2;
items[3] = columnForRow3;
...
3 ,
10 , 40 25 .
items, ,
, , -
. ,
items 78, 160,
.
.
, items ,
int-:
int[][] items;
items -
, :
items = new int[4][];
, , -
columnForRow0
items, .
, columnForRow0,
285
items. -
:
columnForRow0[1] = 99;
items[0][1] = 99;
,
, .
Java, . Java , -
, .
-
, .
, -
( 52 ).
, .
Microsoft Visual Studio 2015 Cards,
\Microsoft Press\VCSBS\Chapter 10\Cards .
, -
. Card Game
North, South, East West.
, (). , -
. Deal () (.10.2).
-
Windows (Universal Windows Platform (UWP)), UWP-,
, .
Deal. . , ,
, .
Visual Studio 2015
.
Value.cs -
. Value,
:
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack,
Queen, King, Ace }
286 10
. 10.2
Suit.cs. , -
:
enum Suit { Clubs, Diamonds, Hearts, Spades }
PlayingCard.cs .
PlayingCard, .
class PlayingCard
{
private readonly Suit suit;
private readonly Value value;
, -
. .
-
, .
, .
CardValue CardSuit,
, ToString
.
- CardValue CardSuit
, , 15.
Pack.cs. Pack, -
. Pack
NumSuits CardsPerSuit,
. -
. cardPack
PlayingCard. -
,
. randomCardSelector , -
Random. randomCardSelector
:
class Pack
{
public const int NumSuits = 4;
public const int CardsPerSuit = 13;
private PlayingCard[,] cardPack;
private Random randomCardSelector = new Random();
...
}
Pack .
, // TODO:.
288 10
, -
, cardPack
:
public Pack()
{
this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
}
Pack , .
cardPack
:
public Pack()
{
this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
{
for (Value value = Value.Two; value <= Value.Ace; value++)
{
this.cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
}
}
}
for
Suit, ,
.
PlayingCard
cardPack.
. suit value .
, , ,
int-.
Pack DealCardFromPack.
, ,
,
.
.
, NotImplementedException,
, :
public PlayingCard DealCardFromPack()
{
Suit suit = (Suit)randomCardSelector.Next(NumSuits);
}
289
Next,
randomCardSelector
, . Next -
, -
. , int, ,
Suit-, -
.
, .
-
.
while,
. IsSuitEmpty, -
, ( -
). ,
(
) . ,
,
:
public PlayingCard DealCardFromPack()
{
Suit suit = (Suit)randomCardSelector.Next(NumSuits);
while (this.IsSuitEmpty(suit))
{
suit = (Suit)randomCardSelector.Next(NumSuits);
}
}
,
.
. , -
, , , ,
. , :
IsCardAlreadyDealt (
), , , ,
, ,
, .
, DealCardFromPack
, :
public PlayingCard DealCardFromPack()
{
...
Value value = (Value)randomCardSelector.Next(CardsPerSuit);
290 10
, .
DealCardFromPack
cardPack -
null:
public PlayingCard DealCardFromPack()
{
...
PlayingCard card = this.cardPack[(int)suit, (int)value];
this.cardPack[(int)suit, (int)value] = null;
return card;
}
IsSuitEmpty. , -
Suit , ,
.
, NotImplementedException,
, :
private bool IsSuitEmpty(Suit suit)
{
bool result = true;
for (Value value = Value.Two; value <= Value.Ace; value++)
{
if (!IsCardAlreadyDealt(suit, value))
{
result = false;
break;
}
}
return result;
}
IsCardAlreadyDealt (
) , cardPack
.
, result false
break . ,
, result true.
result
.
291
IsCardAlreadyDealt.
, -
. , DealCardFromPack
cardPack
null. ,
:
private bool IsCardAlreadyDealt(Suit suit, Value value)
=> (this.cardPack[(int)suit, (int)value] == null);
true, cardPack
null, false .
. Hand.cs.
Hand, , (
, ).
int-
HandSize , ,
(13).
PlayingCard, HandSize.
playingCardCount , -
, :
class Hand
{
public const int HandSize = 13;
private PlayingCard[] cards = new PlayingCard[HandSize];
private int playingCardCount = 0;
...
}
ToString , ,
. foreach
cards,
PlayingCard ToString.
(\n):
public override string ToString()
{
string result = "";
foreach (PlayingCard card in this.cards)
{
result += $"{card.ToString()}\n";
}
return result;
}
292 10
Hand AddCardToHand.
, , .
, :
public void AddCardToHand(PlayingCard cardDealt)
{
if (this.playingCardCount >= HandSize)
{
throw new ArgumentException("Too many cards");
}
this.cards[this.playingCardCount] = cardDealt;
this.playingCardCount++;
}
, -
. , ArgumentException (
, ). -
cards , playingCardCount,
.
MainPage.xaml -
MainPage.xaml.cs.
Card Game. dealClick.
, Deal.
try- ,
, .
try- , :
private void dealClick(object sender, RoutedEventArgs e)
{
try
{
pack = new Pack();
}
catch (Exception ex)
{
...
}
}
. ,
-
. ,
.
try- , :
293
try
{
pack = new Pack();
for (int handNum = 0; handNum < NumHands; handNum++)
{
hands[handNum] = new Hand();
}
}
catch (Exception ex)
{
...
}
for ,
, hands.
, .
for , :
try
{
...
for (int handNum = 0; handNum < NumHands; handNum++)
{
hands[handNum] = new Hand();
for (int numCards = 0; numCards < Hand.HandSize; numCards++)
{
PlayingCard cardDealt = pack.DealCardFromPack();
hands[handNum].AddCardToHand(cardDealt);
}
}
}
catch (Exception ex)
{
...
}
for -
DealCardFromPack,
, AddCardToHand,
, .
for ,
:
try
{
...
for (int handNum = 0; handNum < NumHands; handNum++)
{
...
}
north.Text = hands[0].ToString();
294 10
south.Text = hands[1].ToString();
east.Text = hands[2].ToString();
west.Text = hands[3].ToString();
}
catch (Exception ex)
{
...
}
, ,
.
north, south, east west. ,
, ToString.
- ,
,
.
.
Card Game, Deal. -
, (.10.3).
. 10.3
295
Deal . , -
.
Visual Studio .
-
. , ,
, ,
. ,
.
,
Visual Studio 2015 11.
Visual Studio 2015,
. -
, .
, -
, -
, :
bool[] flags;
- new,
,
, :
bool[] flags = new bool[10];
- , -
- , :
bool[] flags = { true, false, true, false };
Length, :
bool[] flags = ...;
...
int noOfElements = flags.Length;
296 10
,
- , -
. , -
, , :
bool initialElement = flags[0];
- for foreach, :
- bool[] flags = { true, false, true, false };
for (int i = 0; i < flags.Length; i++)
{
Console.WriteLine(flags[i]);
}
foreach (bool flag in flags)
{
Console.WriteLine(flag);
}
, ,
-
, ,
,
. ,
table
-
:
int[,] table;
table = new int[4,6];
.
. ,
items -
, :
int[][] items;
items = new int[4][];
items[0] = new int[3];
items[1] = new int[10];
items[2] = new int[40];
items[3] = new int[25];
11
, :
, -
params;
,
params
;
, , ,
, .
, -
, ,
. --
,
, -
. -
,
, ,
,
. ,
.
,
.
,
298 11
. -
Microsoft Visual C# Console.WriteLine.
,
, .
WriteLine Console:
class Console
{
public static void WriteLine(Int32 value)
public static void WriteLine(Double value)
public static void WriteLine(Decimal value)
public static void WriteLine(Boolean value)
public static void WriteLine(String value)
...
}
WriteLine -
, System,
, C# . , ,
int,
Int32. C#-
9 .
,
. , ,
, .
, , , ?
Console.WriteLine,
, ,
..? .
? . , ,
:
, params.
, params- , -
.
,
, . -
. ,
299
int-, Min
, int-:
class Util
{
public static int Min(int[] paramList)
{
// .
// , ArgumentException, ,
// .
if (paramList == null || paramList.Length == 0)
{
throw new ArgumentException("Util.Min: not enough arguments");
}
// ,
// ,
//
// , , , currentMin
foreach (int i in paramList)
{
// , , ,
// currentMin, currentMin
if (i < currentMin)
{
currentMin = i;
}
}
// currentMin
// , .
return currentMin;
}
}
ArgumentException ,
, -
.
Min int-
first second, :
int[] array = new int[2];
array[0] = first;
array[1] = second;
int min = Util.Min(array);
Min int-
( first, second third) :
300 11
, -
, :
, . ,
:
int min = Util.Min(new int[] {first, second, third});
, ,
.
,
Min .
params-,
.
params,
. , , Min,
, params-:
class Util
{
public static int Min(params int[] paramList)
{
// ,
}
}
params Min -
, ,
, .
,
:
int min = Util.Min(first, second);
, :
int[] array = new int[2];
array[0] = first;
array[1] = second;
int min = Util.Min(array);
301
, , -
, :
int min = Util.Min(first, second, third);
Min ( , )
Min, params.
, Min
int-. int-,
int- , ,
, .
C C++
params varargs
stdarg.h. Java varargs, -
, params C#.
params- .
params .
:
//
public static int Min(params int[,] table)
...
, params,
. , -
params .
:
// :
public static int Min(int[] paramList)
...
public static int Min(params int[] paramList)
...
params- ref
out:
//
public static int Min(ref params int[] paramList)
...
public static int Min(out params int[] paramList)
...
params . ( ,
params-.)
:
302 11
//
public static int Min(params int[] paramList, int i)
...
, params,
params -. ,
:
Min , -
int-. -
int-.
. ,
params-, ,
-
.
params object[ ]
int- .
int-. , -
, ? C#
. , object -
,
( )
(boxing), , 8
. object
, object-,
. -
:
class Black
{
public static void Hole(params object[] paramList)
...
}
Black.Hole ( ),
.
303
,
object-, 0:
Black.Hole();
// Black.Hole(new object[0]);
Black.Hole , null.
, -
null :
Black.Hole(null);
Black.Hole .
, , ,
:
object[] array = new object[2];
array[0] = "forty two";
array[1] = 42;
Black.Hole(array);
Black.Hole ,
object-:
Black.Hole("forty two", 42);
// Black.Hole(new object[]{"forty two", 42});
CONSOLE.WRITELINE
Console WriteLine.
:
public static void WriteLine(string format, params object[] arg);
WriteLine
, C#
. WriteLine -
, ,
, ( {i} i- -
, ).
( fname lname , mi char,
age int):
Console.WriteLine("Forename:{0}, Middle Initial:{1}, Last name:{2},
Age:{3}", fname, mi, lname, age);
:
Console.WriteLine("Forename:{0}, Middle Initial:{1}, Last name:{2},
Age:{3}", new object[4]{fname, mi, lname, age});
304 11
params-
Sum. -
int- int-.
Sum, params int[].
params, ,
Sum . Sum
.
, params-
Microsoft Visual Studio 2015 ParamsArray,
\Microsoft Press\VCSBS\Chapter 11\ParamsArray -
.
ParamsArray Program.cs Program,
doWork, . Sum
Util (
utility), .
ParamsArray, ParamsArray,
(Add), (Class).
ParamsArray
. (Name) Util.cs,
(Add). -
Util.cs. Util,
ParamsArray.
Util Sum.
int- params- int-
paramList. :
public static int Sum(params int[] paramList)
{
}
Sum paramList.
,
null .
,
ArgumentException. (, ,
,
.)
305
Sum , . -
ArgumentException, paramList null.
Sum :
Sum ,
ArgumentException,
:
public static int Sum(params int[] paramList)
{
if (paramList == null)
{
throw new ArgumentException("Util.Sum: null parameter list");
}
if (paramList.Length == 0)
{
throw new ArgumentException("Util.Sum: empty parameter list");
}
}
, -
. foreach; , -
.
, , -
sumTotal 0:
public static int Sum(params int[] paramList)
{
...
if (paramList.Length == 0)
{
throw new ArgumentException("Util.Sum: empty parameter list");
}
int sumTotal = 0;
}
Sum foreach, -
paramList. foreach
sumTotal.
return -
sumTotal. :
306 11
, ,
.
Util.Sum
Program.cs doWork -
// TODO: :
Console.WriteLine(Util.Sum(null));
.
, :
Exception: Util.Sum: null parameter list
. ,
Visual Studio 2015.
Console.WriteLine,
doWork, :
Console.WriteLine(Util.Sum());
.
.
. ,
:
Exception: Util.Sum: empty parameter list
. ,
Visual Studio 2015.
Console.WriteLine,
doWork, :
Console.WriteLine(Util.Sum(10, 9, 8, 7, 6, 5, 4, 3, 2, 1));
307
. , -
, 55.
, Visual Stu
dio2015.
3 -
, , .
, ,
, , , -
. .
, , -
,
. ,
, , -
, ,
.
, ,
,
. , ,
.
,
( ), -
,
.
. , -
, , -
, ,
,
.
.
Visual Studio 2015 ParamsArray
Util.cs. Sum Util
Console.WriteLine:
308 11
Util Sum.
int-,
.
Using optional parameters (
),
. -
:
class Util
{
...
public static int Sum(int param1 = 0, int param2 = 0, int param3 = 0,
int param4 = 0)
{
Console.WriteLine("Using optional parameters");
int sumTotal = param1 + param2 + param3 + param4;
return sumTotal;
}
}
Program.cs. doWork
:
Console.WriteLine(Util.Sum(2, 4, 6, 8));
Sum, int-.
Sum.
,
, -
:
Using optional parameters
20
, , -
.
. Visual Studio.
doWork , Sum, -
(8):
Console.WriteLine(Util.Sum(2, 4, 6));
309
,
, -
:
Using optional parameters
12
- , ,
,
. C#
, , ,
, .
Visual Studio.
doWork , Sum,
:
Console.WriteLine(Util.Sum(2, 4, 6, 8, 10));
,
, -
:
Using parameter list
30
, , -
, ,
, .
Visual Studio.
,
, .
, params- object
, .
, , ,
, -
, , .
,
Visual Studio 2015 12 .
310 11
, - , params-
. , ,
bool-,
:
someType Method(params bool[] flags)
{
...
}
, - , params-,
object, :
someType Method(params object[] paramList)
{
...
}
12
, :
, ;
new, virtual override;
-
protected;
,
.
-
. , -
,
. ,
,
, ,
. -
, ,
, , ?
, ,
.
.
?
, ,
.
- , -
. - - ,
312 12
, . ,
, .
,
.
, , ,
. , , -
, ,
, . (
, ,
..),
( , ).
?
Horse () Whale ().
, -
, Trot (
) Swim ( ). ,
, Breathe
SuckleYoung?
, -
, ,
Human Aardvark.
, C# -
. , ,
, Mammal (-
), ,
. , Horse, Whale, Human Aardvark
Mammal. -
Mammal (Breathe, SuckleYoung
..), ,
: Trot
Horse Swim Whale.
, Breathe (),
Mammal.
, ,
:
class :
{
...
}
313
, -
. C# ,
,
.
. , -
,
, (-
13
):
class :
{
...
}
, Mammal,
Breathe SuckleYoung,
:
class Mammal
{
public void Breathe()
{
...
}
public void SuckleYoung()
{
...
}
...
}
, ,
,
:
class Horse : Mammal
{
...
public void Trot()
{
...
}
}
C++ ,
,
, . C#
. Java,
extends.
Whale,
Swim, Breathe SuckleYoung. Trot , -
Horse.
, .
,
, ,
.
System.ValueType. ( 13.) -
, Microsoft .NET Framework
,
. ValueType
.
System.Object
System.Object . -
, System.Object. -
C# Mammal
(, ,
):
class Mammal : System.Object
{
...
}
System.Object
,
Mammal, Horse Whale. ,
315
System.Object. , ToString (
2 , -
), ,
.
-
.
. ,
. , -
. ( ,
.)
, -
,
. -
base:
class Mammal //
{
public Mammal(string name) //
{
...
}
...
}
-
,
-
. ,
class Horse : Mammal
{
public Horse(string name)
316 12
{
...
}
...
}
:
class Horse : Mammal
{
public Horse(string name)
: base()
{
...
}
...
}
, Mammal -
. ( ,
, ,
- ), -
,
.
, -
new. ,
C# , -
. , -
Mammal, Horse Whale , ,
:
class Mammal
{
...
}
class Horse : Mammal
{
...
}
class Whale : Mammal
{
...
}
...
Horse myHorse = new Horse(...);
Whale myWhale = myHorse; //
317
,
, -
. :
Horse myHorse = new Horse(...);
Mammal myMammal = myHorse; // , Mammal Horse
, (Horse )
(Mammal), Horse -
Mammal. , Horse
Mammal: ,
Mammal, ,
, Horse. , -
Mammal- Whale-.
: Horse- Whale- Mammal-
,
Mammal. , Horse
Whale, Mammal :
Horse myHorse = new Horse(...);
Mammal myMammal = myHorse;
myMammal.Breathe(); // - Breathe Mammal
myMammal.Trot(); // - Trot Mammal
, object-
. , object System.Object
System.Object , .
, .
Mammal- Horse-:
Mammal myMammal = newMammal(...);
Horse myHorse = myMammal; //
, ,
Mammal-, ,
(Horse), (Whale). Mammal-
Horse- ,
as or ,
, -
cast ( as or,
7 ).
as , myMammal
Horse-, ,
myHorseAgain ,
318 12
Horse-. myMammal -
(Mammal), as
, null:
Horse myHorse = new Horse(...);
Mammal myMammal = myHorse; // myMammal Horse
...
Horse myHorseAgain = myMammal as Horse; // : myMammal Horse
...
Whale myWhale = new Whale(...);
myMammal = myWhale;
...
myHorseAgain = myMammal as Horse; // null - myMammal Whale
.
,
, ,
. -
, ,
.
,
, .
, , -
, .
( ) ,
. ,
, , Horse.Talk
Mammal.Talk:
class Mammal
{
...
public void Talk() // ,
//
{
...
}
}
,
. Horse
Talk, ,
Mammal. Talk Horse
Talk Mammal, Horse.Talk.
,
.
, Mammal.Talk,
, new:
class Mammal
{
...
public void Talk()
{
...
}
}
new , -
- . .
, new : , ,
.
.
ToString System.Object. ToString
.
System.Object
, .
320 12
ToString, System.Object, ,
?
,
.
ToString System.Object. , ,
, , Mammal Horse.
. ?
.
, , , ToString
, -
. . -
ToString, System.Object,
. ,
ToString ,
, System.Object.
System.Object ,
, ToString
.
, , . -
.
, ,
, , -
, ,
. ,
, .
, -
virtual. , ToString System.Object
:
namespace System
{
class Object
{
public virtual string ToString()
{
...
}
...
}
...
}
321
Java, -
, C# .
override
,
override:
class Horse : Mammal
{
...
public override string ToString()
{
...
}
}
-
,
base:
public override string ToString()
{
string temp = base.ToString();
...
}
, -
,
virtual override.
,
. ,
. -
,
, .
-
: ,
.
.
,
. , ,
, .
322 12
override, , .
,
. , -
, , ,
, new.
.
,
virtual, .
,
, , -
. ,
Mammal:
class Mammal
{
...
public virtual string GetTypeName()
{
return "This is a mammal" ;
}
}
: -, override,
GetTypeName Horse Whale,
-, , Aardvark GetTypeName.
:
Mammal myMammal;
Horse myHorse = new Horse(...);
Whale myWhale = new Whale(...);
Aardvark myAardvark = new Aardvark(...);
myMammal = myHorse;
Console.WriteLine(myMammal.GetTypeName()); // Horse
myMammal = myWhale;
Console.WriteLine(myMammal.GetTypeName()); // Whale
myMammal = myAardvark;
Console.WriteLine(myMammal.GetTypeName()); // Aardvark
Console.
WriteLine?
This is a mammal, GetTypeName -
myMammal, Mammal.
, myMammal Horse. (-
, Horse- Mammal-,
Horse Mammal.) GetTypeName
, ,
Horse.GetTypeName, -
This is a horse. -
Console.WriteLine, This is a whale.
Console.WriteLine Aardvark.
Aardvark GetTypeName,
, Mammal This is a mammal.
-
,
.
public private
: ,
.
-
. ,
- , -
.
,
.
324 12
, -
,
.
protected. .
,
. ,
.
, -
. , -
.
C#
. -
, , , -
. ,
-
.
, .
,
.
-
, ,
.
.
Vehicle Airplane Car.
Vehicle StartEngine
StopEngine, ,
, .
, Vehicle Drive,
, -
.
Microsoft Visual Studio 2015 Vehicles,
\Microsoft Press\VCSBS\Chapter 12\Vehicles . -
Vehicles Program.cs, Program
Main doWork, .
325
Vehicles,
, . -
,
. Vehicle.cs
. Vehicle.cs, -
.
Vehicle.
Vehicle StartEngine StopEngine,
:
class Vehicle
{
public void StartEngine(string noiseToMakeWhenStarting)
{
Console.WriteLine($"Starting engine: {noiseToMakeWhenStarting}");
}
, -
Vehicle. noiseToMakeWhenStarting (
) noiseToMakeWhenStopping ( )
,
.
.
. Airplane.cs
. , -
Airplane, .
Airplane ,
, Vehicle:
class Airplane : Vehicle
{
}
Project . -
. Car.cs -
. ,
Car, .
Car , ,
Vehicle:
class Car : Vehicle
{
}
Vehicle.cs. Vehicle -
Drive, :
class Vehicle
{
...
public virtual void Drive()
{
Console.WriteLine("Default implementation of the Drive method");
}
}
Program.cs. doWork
//TODO: , Airplane
, :
327
doWork -
, .
Car .
static void doWork()
{
...
Console.WriteLine("\nJourney by car:");
Car myCar = new Car();
myCar.StartEngine("Brm brm");
myCar.Accelerate();
myCar.Drive();
myCar.Brake();
myCar.StopEngine("Phut phut");
}
. ,
,
(.12.1).
,
Drive,
.
. 12.1
328 12
, Visual Studio2015.
Airplane. Airplane -
Drive, :
class Airplane : Vehicle
{
...
public override void Drive()
{
Console.WriteLine("Flying");
}
}
IntelliSense .
IntelliSense Drive, Visual Studio
, base.Drive. -
, .
Car. Car
Drive, :
class Car : Vehicle
{
...
public override void Drive()
{
Console.WriteLine("Motoring");
}
}
.
, Airplane
Flying, Car Motoring (.12.2).
. 12.2
329
, Visual Stu
dio2015.
Program.cs. doWork -
, :
static void doWork()
{
...
Console.WriteLine("\nTesting polymorphism");
Vehicle v = myCar;
v.Drive();
v = myPlane;
v.Drive();
}
, -
Drive. Vehicle- -
Car ( , Car-
Vehicle-), Vehicle-
Drive. Vehicle-
Airplane , -
Drive.
. ,
, ,
(.12.3):
Testing polymorphism
Motoring
Flying
. 12.3
330 12
Drive , ( -
) , Drive
Vehicle-, ,
. Vehicle-
Car, Car.Drive. Vehicle-
Airplane, Airplane.Drive.
, Visual Stu
dio2015.
, -
, -
.
,
, .
, , int
Negate, ,
, .
(,
(), .)
NegInt32, System.Int32 (int -
System.Int32), Negate:
class NegInt32 : System.Int32 // !
{
public int Negate()
{
...
}
}
Negate NegInt32
, System.Int32.
.
NegInt32, -
int-,
int- NegInt32.
System.Int32 , ,
.
331
.
( ) . -
,
.
this ,
. ,
Negate int:
static class Util
{
public static int Negate(this int i)
{
return -i;
}
}
,
this, -
Negate, , this, int
, int.
, Util
. ( , using,
, Util, using
static, Util.)
(.):
int x = 591;
Console.WriteLine($"x.Negate {x.Negate()}");
, Util - ,
Negate, . C# -
,
. Util.Negate,
int- -
,
:
int x = 591;
Console.WriteLine($"x.Negate {Util.Negate(x)}");
int .
332 12
int - 10
.
Visual Studio 2015 ExtensionMethod,
\Microsoft Press\VCSBS\Chapter 12\ExtensionMethod .
Util.cs.
Util, Extensions. ,
.
, //TODO:.
Util
ConvertToBase. : int-
i, this, -
, int, int-
baseToConvertTo ( ).
, i,
, baseToConvertTo.
int- .
ConvertToBase :
static class Util
{
public static int ConvertToBase(this int i, int baseToConvertTo)
{
}
}
ConvertToBase if, ,
baseToConvertTo 2 10.
, , -
. baseToConvertTo
, .
ConvertToBase :
public static int ConvertToBase(this int i, int baseToConvertTo)
{
if (baseToConvertTo < 2 || baseToConvertTo > 10)
{
throw new ArgumentException("Value cannot be converted to base " +
baseToConvertTo.ToString());
}
}
333
ConvertToBase ,
ArgumentException, , .
,
10 . (
5
.)
public static int ConvertToBase(this int i, int baseToConvertTo)
{
...
int result = 0;
int iterations = 0;
do
{
int nextDigit = i % baseToConvertTo;
i /= baseToConvertTo;
result += nextDigit * (int)Math.Pow(10, iterations);
iterations++;
}
while (i != 0);
return result;
}
, UTIL,
. , Program.cs
ConvertToBase .
doWork Program ,
, //TODO::
static void doWork()
{
int x = 591;
for (int i = 2; i <= 10; i++)
{
Console.WriteLine($"{x} in base {i} is {x.ConvertToBase(i)}");
}
}
int- x 591.
( .)
591
334 12
2 10 (.12.4). ,
ConvertToBase IntelliSense,
Console.WriteLine x (.).
. 12.4
. , -
, 591
(.12.5).
. 12.5
335
,
, , -
.
.
,
Visual Studio 2015 13.
Visual Studio 2015,
. -
, .
,
, :
class DerivedClass : BaseClass
{
...
}
-
- base
-
, :
class DerivedClass : BaseClass
{
...
public DerivedClass(int x) : base(x)
{
...
}
...
}
336 12
virtual, :
class Mammal
{
public virtual void Breathe()
{
...
}
...
}
-
, override, :
class Whale : Mammal
- {
public override void Breathe()
{
...
}
...
}
-
. ,
this, :
static class Util
{
public static int Negate(this int i)
{
return -i;
}
}
13
, :
,
;
;
;
;
,
.
, ,
, -
.
, ,
, .
,
.
, ,
.
, , -
, -
.
, ,
, ,
.
338 13
, ,
, . ,
, RetrieveInOrder,
,
, . (
, -
.) -
, , -
,
, ,
, -
.
, (
), , ,
. , -
,
?
ToString, 12 ,
,
.
. -
,
. , ,
-
. ,
, CompareTo,
, RetrieveInOrder,
:
int CompareTo(object obj)
{
// , obj
// , , obj
// , , obj
...
}
, CompareTo, -
,
, . , -
. ,
339
, , .
CompareTo
.
,
. , -
. .
,
, .
, -
, class
interface. , , ,
, ,
(public, private protected). , -
,
, ,
. -
, :
interface IComparable
{
int CompareTo(object obj);
}
Microsoft .NET
, I.
C#. , IComparable
System.
, -
, .
, , -
, .
, ,
,
. , ,
, .
340 13
, , Mammal-,
12, , -
(land-bound), NumberOfLegs,
int-
( ). (
.) ILandBound, ,
:
interface ILandBound
{
int NumberOfLegs();
}
Horse. -
( NumberOfLegs):
class Horse : ILandBound
{
...
public int NumberOfLegs()
{
return 4;
}
}
,
:
.
, ref out, .
, , -
. ,
.
- , .
. C#
341
as, ,
, Java. C#
. , ,
.
Horse, Mammal,
ILandBound:
interface ILandBound
{
...
}
class Mammal
{
...
}
InterfaceA ,
InterfaceB. , -
. ,
InterfaceA, ,
InterfaceB, InterfaceA.
, -
, , ,
, ,
. , Horse-
ILandBound-:
Horse myHorse = new Horse(...);
ILandBound iMyHorse = myHorse; //
, (horses) ,
(land-bound mammals),
ILandBound- Horse-
, ,
Horse-, - ,
ILandBound.
,
,
342 13
, ,
. , FindLandSpeed
, ILandBound:
int FindLandSpeed(ILandBound landBoundMammal)
{
...
}
, ,
, is, 8
. is
, ,
, . ,
, myHorse ILandBoun, -
myHorse ILandBound:
if (myHorse is ILandBound)
{
ILandBound iLandBoundAnimal = myHorse;
}
,
, .
, -
.
, .
, -
.
, . , -
, IGrazable (),
ChewGrass ( ) .
Horse :
class Horse : Mammal, ILandBound, IGrazable
{
...
}
,
. ILandBound
343
Horse, , : Horse -
ILandBound, NumberOfLegs ,
ILandBound:
interface ILandBound
{
int NumberOfLegs();
}
- , -
, Horse .
,
. , ,
.
, leg. -
, ,
:
interface IJourney
{
int NumberOfLegs();
}
, Horse,
:
,
? : !
C# , ,
.
344 13
, -
, .
, :
,
.
,
:
(public). , -
, .
. Horse- ,
NumberOfLegs, -
. , Horse .
. Horse,
: ,
ILandBound, , IJourney?
? Horse-
:
.
345
,
, .
.
- , .
.
- . -
.
. -
, ,
. ( 14 -
.)
. -
.
- (, ,
, ).
- ,
.
,
- , - -
.
,
.
IDraw IColor, -
, .
, ,
( ,
, ).
IDraw :
SetLocation
x y;
Draw ,
SetLocation.
346 13
IColor SetColor.
. , .
IDraw IColor
Microsoft Visual Studio 2015 Drawing,
\Microsoft Press\VCSBS\Chapter 13\Drawing .
Drawing .
DrawingPad. canvas
() drawingCanvas.
.
Drawing. -
.
Drawing, Visual C#,
. .
IDraw.cs, .
Visual Studio IDraw.cs . -
IDraw.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Drawing
{
interface IDraw
{
}
}
IDraw.cs using:
using Windows.UI.Xaml.Controls;
Canvas,
Windows.UI.Xaml.Controls
Windows (Universal Windows Platform (UWP)).
IDraw ,
:
interface IDraw
{
void SetLocation(int xCoord, int yCoord);
void Draw(Canvas canvas);
}
347
.
-
. IColor.cs,
. Visual Studio IColor.cs -
. IColor.cs .
IColor.cs using:
using Windows.UI;
Color,
Windows.UI UWP-.
IColor ,
:
interface IColor
{
void SetColor(Color color);
}
IDraw IColor.
.
Square Circle.
.
Square Circle
Project . ,
Drawing .
Square.cs, .
Visual Studio Square.cs .
Square.cs :
using Windows.UI;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
using Windows.UI.Xaml.Controls;
Square (),
IDraw IColor:
class Square : IDraw, IColor
{
}
Square ,
:
348 13
Square -
. Rectangle Windows.UI.Xaml.
Shapes UWP-. -
. Square ,
:
class Square : IDraw, IColor
{
...
public Square(int sideLength)
{
this.sideLength = sideLength;
}
}
sideLength
.
Square IDraw.
(.13.1).
. 13.1
Visual Studio
IDraw . , Square
349
. , Visual Studio,
:
void IDraw.SetLocation(int xCoord, int yCoord)
{
throw new NotImplementedException();
}
NotImplemented
Exception. , .
, IDraw.SetLocation, -
NotImplementedException, ,
:
void IDraw.SetLocation(int xCoord, int yCoord)
{
this.locX = xCoord;
this.locY = yCoord;
}
locX locY
Square.
, IDraw.Draw, ,
:
void IDraw.Draw(Canvas canvas)
{
if (this.rect != null)
{
canvas.Children.Remove(this.rect);
}
else
{
this.rect = new Rectangle();
}
this.rect.Height = this.sideLength;
this.rect.Width = this.sideLength;
Canvas.SetTop(this.rect, this.locY);
Canvas.SetLeft(this.rect, this.locX);
canvas.Children.Add(this.rect);
}
Square- Rectangle-.
( (square) .) Rectangle
(, ),
350 13
, Square . ( rect
null-, .)
Fill rect , -
SolidColorBrush-. ( SolidColorBrush
.)
. -
Drawing Circle.cs, -
. Visual Studio Circle.cs
.
Circle.cs using:
using Windows.UI;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
using Windows.UI.Xaml.Controls;
Circle, -
IDraw IColor, :
class Circle : IDraw, IColor
{
}
Circle , -
:
class Circle : IDraw, IColor
{
private int diameter;
private int locX = 0, locY = 0;
private Ellipse circle = null;
}
351
Circle- .
Ellipse ,
.
Circle , :
class Circle : IDraw, IColor
{
...
public Circle(int diameter)
{
this.diameter = diameter;
}
}
diameter.
Circle SetLocation:
void IDraw.SetLocation(int xCoord, int yCoord)
{
this.locX = xCoord;
this.locY = yCoord;
}
IDraw ,
Square.
Circle Draw:
void IDraw.Draw(Canvas canvas)
{
if (this.circle != null)
{
canvas.Children.Remove(this.circle);
}
else
{
this.circle = new Ellipse();
}
this.circle.Height = this.diameter;
this.circle.Width = this.diameter;
Canvas.SetTop(this.circle, this.locY);
Canvas.SetLeft(this.circle, this.locX);
canvas.Children.Add(this.circle);
}
IDraw.
Draw Square, , Circle-
Ellipse-. (
.)
352 13
Circle SetColor:
void IColor.SetColor(Color color)
{
if (this.circle != null)
{
SolidColorBrush brush = new SolidColorBrush(color);
this.circle.Fill = brush;
}
}
IColor. ,
, Square.
Square Circle ,
.
Square Circle
DrawingPad.xaml. -
, Canvas-,
.
. ( .)
Tapped .
Visual Studio drawingCanvas_Tapped
DrawingPad . , -
, . -
20
.
DrawingPad.xaml.cs using:
using Windows.UI;
Windows.UI Colors,
.
drawingCanvas_Tapped ,
:
private void drawingCanvas_Tapped(object sender, TappedRoutedEventArgs e)
{
Point mouseLocation = e.GetPosition(this.drawingCanvas);
Square mySquare = new Square(100);
if (mySquare is IDraw)
{
353
TappedRoutedEventArgs -
. , GetPosition
Point, x y .
Square-. ,
IDraw ( , ,
),
. ,
. ( SetLocation Draw Square
IDraw.)
Square
. , x y Point
(double),
(int).
Draw Square-.
drawingCanvas_Tapped ,
:
private void drawingCanvas_Tapped(object sender, TappedRoutedEventArgs e)
{
...
if (mySquare is IColor)
{
IColor colorSquare = mySquare;
colorSquare.SetColor(Colors.BlueViolet);
}
}
Square IColor:
, Square -
SetColor Square- Colors.
BlueViolet.
SetColor, Draw,
SetColor Square-,
. SetColor Draw, Square-
.
DrawingPad.xaml
Canvas.
354 13
RightTapped,
.
, -
, ,
.
drawingCanvas_RightTapped ,
:
private void drawingCanvas_RightTapped(object sender,
RightTappedRoutedEventArgs e)
{
Point mouseLocation = e.GetPosition(this.drawingCanvas);
Circle myCircle = new Circle(100);
if (myCircle is IDraw)
{
IDraw drawCircle = myCircle;
drawCircle.SetLocation((int)mouseLocation.X, (int)mouseLocation.Y);
drawCircle.Draw(drawingCanvas);
}
if (myCircle is IColor)
{
IColor colorCircle = myCircle;
colorCircle.SetColor(Colors.HotPink);
}
}
, , , -
drawingCanvas_Tapped, ,
, .
,
.
Drawing Pad, ,
, .
.
,
,
. .
, -
. .13.2 ,
Windows 10.
Visual Studio .
355
. 13.2
ILandBound IGrazable,
,
,
C#-.
.
, :
class Horse : Mammal, ILandBound, IGrazable
{
...
void IGrazable.ChewGrass()
{
Console.WriteLine("Chewing grass");
//
}
}
356 13
. -
, -
.
, . -
, ,
:
class GrazingMammal : Mammal, IGrazable
{
...
void IGrazable.ChewGrass()
{
//
Console.WriteLine("Chewing grass");
}
}
, : -
GrazingMammal ( Mammal).
. GrazingMammal
.
, . GrazingMammal
, .
,
, abstract:
abstract class GrazingMammal : Mammal, IGrazable
{
...
}
357
GrazingMammal-,
:
GrazingMammal myGrazingMammal = new GrazingMammal(...); //
. ,
( 12), -
, .
. -
. GrazingMammal
DigestGrass: -
,
DigestGrass.
,
, , -
.
abstract class GrazingMammal : Mammal, IGrazable
{
public abstract void DigestGrass();
...
}
,
. -
, . ,
.
,
, ,
, ,
. , -
, ,
. C#,
sealed (),
, -
, :
sealed class Horse : GrazingMammal, ILandBound
{
...
}
358 13
- Horse
, . ,
-
.
sealed , -
. ,
.
, overrid, -
sealed override. interface, virtual, override
sealed .
.
-
, . Square Circle
.
DrawingShape, -
Square Circle .
DrawingShape
Visual Studio Drawing.
Drawing, \Microsoft Press\VCSBS\
Chapter 13\Drawing Using Interfaces .
Drawing, -
. .
Drawing.
DrawingShape.cs, . Visual Studio
.
359
DrawingShape.cs
using:
using Windows.UI;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
using Windows.UI.Xaml.Controls;
Circle
Square.
DrawingShape-.
DrawingShape,
( ):
abstract class DrawingShape
{
}
DrawingShape ,
:
abstract class DrawingShape
{
protected int size;
protected int locX = 0, locY = 0;
protected Shape = null;
}
locX locY
Square, Circle, -
.
.
(sideLength diameter),
. size.
Square
Rectangle, Circle Ellipse-.
, Shape,
.NET Framework.
DrawingShape Shape.
DrawingShape :
abstract class DrawingShape
{
...
public DrawingShape(int size)
{
this.size = size;
}
}
360 13
DrawingShape- size.
DrawingShape SetLocation SetColor,
. -
, ,
DrawingShape. ,
. , DrawingShape
IDraw IColor ( -
Square Circle, ),
:
abstract class DrawingShape
{
...
public void SetLocation(int xCoord, int yCoord)
{
this.locX = xCoord;
this.locY = yCoord;
}
DrawingShape Draw. ,
, ,
.
shape null-, . ,
, shape-
. ( , Square
Rectangle, Circle Ellipse.)
this.shape.Height = this.size;
this.shape.Width = this.size;
Canvas.SetTop(this.shape, this.locY);
361
Canvas.SetLeft(this.shape, this.locX);
canvas.Children.Add(this.shape);
}
}
DrawingShape . -
Square Circle,
, .
Square Circle
DrawingShape
Square. Square,
DrawingShape
, IDraw IColor:
class Square : DrawingShape, IDraw, IColor
{
...
}
, , Square,
.
Square sideLength, rect, locX locY.
, DrawingShape.
, -
, :
class Square : DrawingShape, IDraw, IColor
{
public Square(int sideLength)
: base(sideLength)
{
}
...
}
, ,
.
Square IDraw.SetLocation IColor.SetColor. -
DrawingShape.
Draw. public
override, IDraw.
DrawingShape,
, Square:
362 13
Draw , :
public override void Draw(Canvas canvas)
{
if (this.shape != null)
{
canvas.Children.Remove(this.shape);
}
else
{
this.shape = new Rectangle();
}
base.Draw(canvas);
}
shape,
DrawingShape, Rectangle ,
. DrawingShape
Draw.
Circle,
Circle diameter
Draw shape Ellipse-.
Circle :
class Circle : DrawingShape, IDraw, IColor
{
public Circle(int diameter)
: base(diameter)
{
}
base.Draw(canvas);
}
}
363
. Drawing
Pad, , -
Square- (), Circle-
(). , .
Visual Studio .
WINDOWS RUNTIME
9 -
, Windows Windows 8
Windows Runtime (WinRT) -
API- Windows,
. (
, -
.NET Framework; C++,
C#.) .NET Framework
(common language runtime (CLR)).
.NET Framework -
. Windows 7
CLR API-
Windows.
, Windows 10, -
( 4.6),
C#-, Windows 7,
Windows 10.
Windows 10 UWP- -
WinRT. , UWP-, -
, C#, CLR WinRT,
API- Windows. Microsoft
CLR WinRT, -
, .NET Framework,
WinRT.
, Int32 .NET Framework (int C#),
,
WinRT. CLR WinRT -
, WinRT
.NET Framework 4.6. UWP-
,
.NET Framework 4.6. ( IntelliSense Visual Studio 2015
C# UWP-, , -
WinRT.)
WinRT ,
.NET Framework
, .NET Framework, -
364 13
. WinRT
CLR ,
, .NET Framework, -
.
, CLR WinRT, CLR -
, WinRT,
:
, ,
,
WinRT. 9
( WinRT
, ). -
WinRT ,
.
, -
WinRT .NET Framework,
WinRT WinRT.
.NET Framework (,
) , C#
(int, long, float, double, string ..).
, .NET Framework, -
WinRT.
System.Object,
ToString, .
, ,
, , . ,
(, ) Windows.
WinRT
. -
. ,
, -
.
, .NET
Framework, UWP-,
.
, WinRT
.
, WinRT
C#.
.
365
, -
. () () -
,
.13.1.
13.1
abstract
new * **
override ***
private
protected ****
public
sealed
virtual
*
.
** , .
*** , .
**** ,
.
,
Visual Studio 2015 14.
Visual Studio 2015,
. -
, .
366 13
- interface, :
interface IDemo
{
string GetName();
string GetDescription();
}
- , ,
-,
, , :
class Test : IDemo
{
public string IDemo.GetName()
{
...
}
public string IDemo.GetDescription()
{
...
}
}
- , abstract.
, -
- abstract, , :
- abstract class GrazingMammal
{
, - abstract void DigestGrass();
...
}
- , sealed, -
, :
- sealed class Horse
{
...
}
14
, :
, ;
, ;
-
try-finally;
-
using;
IDisposable -
.
, . (, -
,
, .) ,
,
. , , ,
, . .
?
new, ?
.
368 14
, .
new.
Square, 13 -
.
int sizeOfSquare = 99;
Square mySquare = new Square(sizeOfSquare); // Square
, new ,
.
1. new .
.
2. new ,
. .
, C++,
, C# new, ,
.
(.). , Square Draw,
:
mySquare.Draw();
Square, -
DrawingShape -
IDraw. 13.
mySquare ,
Square- . ,
. ( , -
.) ,
.
1. (common language runtime (CLR)) -
.
.
2. CLR , , ; ,
, .
.
369
, C++,
, C# delete. CLR.
, , -
. CLR
, ,
.
(, ), ,
, , null-.
, ,
.
. , ,
, Windows. , ,
, ,
. , ,
- . (
using, .)
, ,
, CLR
. (~),
. , , -
. (, ,
.)
class FileProcessor
{
FileStream file = null;
public FileProcessor(string fileName)
{
this.file = File.OpenRead(fileName); // open file for reading
}
~FileProcessor()
{
this.file.Close(); // close file
}
}
370 14
.
-
, , :
struct MyStruct
{
~MyStruct() { ... } //
}
, public.
,
CLR, :
public ~FileProcessor() { ... } //
- . -
, :
~FileProcessor(int parameter) { ... } //
C#, , -
Object.Finalize.
class FileProcessor
{
~FileProcessor() { // }
}
:
class FileProcessor
{
protected override void Finalize()
{
try { // }
finally { base.Finalize(); }
}
}
Finalize try-
, finally, -
Finalize. ( try finally
6 .) ,
, -
.
, . -
, Finalize,
Finalize.
371
?
, C#, .
. CLR -
. , ,
. -
FileProcessor myFp
referenceToMyFp:
FileProcessor myFp = new FileProcessor();
FileProcessor referenceToMyFp = myFp;
? ! -
. CLR
. myFp , -
, - (
referenceToMyFp) , FileProcessor,
( ). , -
.
,
, .
, , -
C# .
,
.
. , (
) ,
. .
,
.
, , ,
, .
, -
, .
.
.
, .
, C#,
, .
372 14
.
.
, .
,
.
.
, ,
.
,
, - .
-
.
? .
, , . ,
, .
, CLR
( ,
, ),
.
, .
,
Collect GC, System.
. GC.Collect
,
GC.Collect -
, , , -
. CLR.
,
. ,
, , , : -
, .
, , ,
, . ,
,
.
?
-
,
373
. ,
, ,
,
, .
. Windows
,
.
,
-
. -
.
,
, , ( -
Microsoft
), , ,
, .
1. ,
.
,
. , ,
.
2. , ,
( (freachable)).
, ,
, , .
3. ,
( ), -
,
. ,
.
4. .
5. ,
(, freachable-), -
Finalize.
, ,
. ,
374 14
freachable-
. ,
. , -
, ,
. (
using.)
. -
, ,
, -
. , -
.
. , ,
, .
, -
, ,
. -
, ,
, .
. , ,
. -
, .
(disposal method) -
, . , -
C# .
, , -
TextReader System.IO.
.
TextReader Close, .
StreamReader, ,
, StringReader, ,
TextReader,
Close. ,
StreamReader :
375
ReadLine
. , ReadLine
null. , Close
, -
. :
. ReadLine WriteLine -
, Close
. ,
.
, -
Close, , ,
finally. , -
, :
TextReader reader = new StreamReader(filename);
try
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
finally
{
reader.Close();
}
finally ,
, .
,
. (
try finally.)
, ,
. (,
376 14
, null-
finally, null-.)
. , -
,
.
finally .
,
.
using.
using IDisposable
using -
. ,
, using.
using, , -
using, . ,
, , -
.
using :
using ( type variable = initialization )
{
StatementBlock
}
Close TextReader:
using (TextReader reader = new StreamReader(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
using :
{
TextReader reader = new StreamReader(filename);
try
{
377
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
finally
{
if (reader != null)
{
((IDisposable)reader).Dispose();
}
}
}
using
. , , -
using,
-
.
, using, ,
IDisposable.
System Dispose:
namespace System
{
interface IDisposable
{
void Dispose();
}
}
Dispose -
. , StreamReader
IDisposable, Dispose Close, .
using , -
,
. ,
, try-finally.
, :
,
;
;
. -
, using (
reader), using,
378 14
,
.
Dispose
IDisposable, using
? , -
, . ,
Dispose, , , ,
, ,
using. Dispose
. .
Dispose, ,
, .
,
IDisposable:
class Example : IDisposable
{
private Resource scarce; //
...
Example.
IDisposable.
Dispose
.
Dispose
Dispose, ,
true. -
.
Dispose,
, -
false.
.
Dispose . -
disposed , , -
. (
Dispose, , ,
Dispose CLR
.) .
Dispose
(, ) (-
, ). disposing
true, Dispose.
.
disposing false,
.
(
380 14
),
.
Dispose GC.SuppressFinalize.
, .
, SomeBehavior, ,
, .
-
using -
. ,
,
.
Calculator, ,
. -
- -
. , ,
IDisposable.
,
Microsoft Visual Studio 2015 ,
. . -
Visual C#
. .
, , GarbageCollectionDemo.
Microsoft Press\VCSBS\Chapter 14
OK.
-
, , Microsoft Press\VCSBS\
Chapter 14.
GarbageCollectionDemo. ,
. Calculator.cs
. Calculator,
.
Calculator Divide (
):
class Calculator
{
public int Divide(int first, int second)
{
return first / second;
}
}
, -
.
, .
Divide Calculator -
, :
class Calculator
{
public Calculator()
{
Console.WriteLine("Calculator being created");
}
...
}
,
Calculator-.
Calculator ,
:
class Calculator
{
...
~Calculator()
{
Console.WriteLine("Calculator being finalized");
}
...
}
, ,
, .
-
- .
382 14
Calculator-, Divide (-
), ,
.
. , -
:
, Calculator-
, ,
Main.
Visual Studio 2015.
CLR , , -
, , , -
. ,
Calculator- ,
CLR .
, -
, ,
, , ,
. ,
;
,
.
, , -
, .
Calculator
IDisposable, Calculator- -
.
383
IDisposable
Calculator.cs.
Calculator, IDisposable (-
):
class Calculator : IDisposable
{
...
}
Calculator Dispose. -
IDisposable:
class Calculator : IDisposable
{
...
public void Dispose()
{
Console.WriteLine("Calculator being disposed");
}
}
Dispose , , -
. ,
Console.WriteLine, ,
, Dispose . -
-
Dispose. ,
, .
Dispose ,
Dispose , ,
Dispose.
, ,
Dispose. ( ,
, , ,
.)
~Calculator()
{
Console.WriteLine("Calculator being finalized");
this.Dispose();
}
Calculator-, Dispose
-
( , calculator.Dispose()),
Calculator- using.
.
384 14
Program.cs. Main,
Calculator- Divide, , -
:
static void Main(string[] args)
{
using (Calculator calculator = new Calculator())
{
Console.WriteLine($"120 / 15 = {calculator.Divide(120, 15)}");
}
Console.WriteLine("Program finishing");
}
. ,
:
Calculator being created
120 / 15 = 8
Calculator being disposed
Program finishing
Calculator being finalized
Calculator being disposed
using Dispose , -
Program finishing.
, Calculator- - -
Dispose.
, .
Visual Studio 2015.
-
, ,
.
, ,
Dispose, .
Calculator.cs. Calculator -
disposed , ,
false:
class Calculator : IDisposable
{
private bool disposed = false;
...
}
385
-
Dispose.
Dispose , -
, disposed false.
disposed true ( -
):
public void Dispose()
{
if (!this.disposed)
{
Console.WriteLine("Calculator being disposed");
}
this.disposed = true;
}
. , -
:
Calculator being created
120 / 15 = 8
Calculator being disposed
Program finishing
Calculator being finalized
Calculator- ,
. , -
, .
Visual Studio 2015.
Dispose Calculator ,
:
public void Dispose()
{
if (!this.disposed)
{
Console.WriteLine("Calculator being disposed");
}
this.disposed = true;
GC.SuppressFinalize(this);
}
GC
, -
. SuppressFinalize, ,
,
.
386 14
GC ,
. , ,
CLR,
-
. SuppressFinalize ,
( , , ,
, , ).
, , ,
, .
. , -
:
Calculator being created
120 / 15 = 8
Calculator being disposed
Program finishing
, , Calculator-
.
Visual Studio 2015.
disposed -
, ,
. , -
,
,
. ,
, Dispose, -
.
disposed
Dispose, -
,
, .
, C# lock
, :
public void Dispose()
{
lock(this)
{
if (!disposed)
387
{
Console.WriteLine("Calculator being disposed");
}
this.disposed = true;
GC.SuppressFinalize(this);
}
}
lock
. lock (-
this) . , -
, lock.
lock, , -
, ,
. , ,
lock,
,
. , ,
disposed true,
if (!disposed).
, -
. ,
, -
. ( ,
, :
,
, , -
.)
Dispose: using Dispose(),
Dispose(true),
Dispose(false). -
, Dispose
true.
Dispose .
using -
,
.
, -
, using.
Program.cs. ,
Divide Calculator, , :
388 14
120 0.
.
DivideByZeroException.
GarbageCollectionDemo (.14.1).
( .)
. 14.1
,
.
. 14.2
, .NET
Framework -
, . ,
. , -
using -
IDisposable
.
, -
Visual Studio 2015 15
.
Visual Studio 2015,
. -
, .
- , -
(~).
(, public),
, :
390 14
class Example
{
~Example()
{
...
}
}
- .
GC.Collect
( -
)
- ( -
) , :
class TextReader
( {
...
- public virtual void Close()
{
...
-
}
- }
) class Example
{
void Use()
{
TextReader reader = ...;
// reader
reader.Close();
}
}
IDisposable, :
- class SafeResource : IDisposable
- {
...
- public void Dispose()
{
//
}
}
- using, :
- using (SafeResource resource = new SafeResource())
{
// SafeResource
- ...
, - }
IDisposable
III
C#
-
C#, ,
, . ,
(common language runtime (CLR))
, ,
C#. III,
, -
C#
,
.
III C#: , -
, . , -
, ,
,
, .
C# (Language-Integrated
Query (LINQ)), -
. ,
C# .
15
, :
;
, -
get;
, -
set;
, ;
, , -
;
;
.
.
,
,
. ,
,
.
.
, ,
(
) . -
.
393
.
, -
x y. ,
x 0 1280, y 0
1024:
struct ScreenPosition
{
public int X;
public int Y;
, , ,
,
. ,
, .
, ScreenPosition , ,
,
.
( , )
394 15
,
X, Y :
ScreenPosition origin = new ScreenPosition(0, 0);
...
int xpos = origin.X;
origin.Y = -100; // !
, -
,
-
.
. , X
(GetX) (SetX). , SetX -
:
struct ScreenPosition
{
...
public int GetX()
{
return this.x;
}
, . -
ScreenPosition
, , -
. X
10. , X,
GetX, X, -
SetX.
int xpos = origin.GetX();
origin.SetX(xpos + 10);
, X:
origin.X += 10;
? 395
,
, , , , . -
, (
), ,
, .
?
: ,
.
, . -
, , ,
, (getters)
(setters) .
:
AccessModifier Type PropertyName
{
get
{
//
}
set
{
//
}
}
,
get set. get , ,
set , .
, -
, get set.
ScreenPosition,
. , :
_x _y
;
X Y -
;
, ,
value:
396 15
struct ScreenPosition
{
private int _x, _y;
public int X
{
get { return this._x; }
set { this._x = rangeCheckedX(value); }
}
public int Y
{
get { return this._y; }
set { this._y = rangeCheckedY(value); }
}
-
, -
. ,
get .
,
,
.
, ,
.
,
2 ,
. , , -
. , , ScreenPosition
, _x _y.
.
7
? 397
, ,
, , -
, ,
. , ,
,
.
,
. ,
Employee. employeeID ,
EmployeeID :
class Employee
{
private int employeeID;
public int EmployeeID
{
get { return this.EmployeeID; }
set { this.EmployeeID = value; }
}
}
, -
EmployeeID
StackOverflowException. , get set
( E),
( e), -
,
. !
, ,
, - -
.
-
.
(
) ( ).
, X Y -
ScreenPosition:
ScreenPosition origin = new ScreenPosition(0, 0);
int xpos = origin.X; // origin.X.get
int ypos = origin.Y; // origin.Y.get
398 15
,
. , -
, ,
, get . ,
, ,
, , set :
origin.X = 40; // origin.X.set value, 40
origin.Y = 100; // origin.Y.set value, 100
,
set value.
.
/.
, get, set. ,
, ,
get set:
origin.X += 10;
,
.
, .
, get.
. ,
X ScreenPosition :
struct ScreenPosition
{
private int _x;
...
public int X
{
get { return this._x; }
}
}
X set, , -
, X :
origin.X = 140; //
? 399
,
set. -
. , X
ScreenPosition :
struct ScreenPosition
{
private int _x;
...
public int X
{
set { this._x = rangeCheckedX(value); }
}
}
X get,
, X :
Console.WriteLine(origin.X); //
origin.X = 200; //
origin.X += 10; //
, ,
, . , -
, ,
.
. , ,
.
, -
public, private protected.
get set .
, ScreenPosition -
set X Y (private). (
get , .)
struct ScreenPosition
{
private int _x, _y;
...
public int X
{
get { return this._x; }
400 15
public int Y
{
get { return this._y; }
private set { this._y = rangeCheckedY(value); }
}
...
}
.
. , -
, .
, -
, , . -
, (private),
(public). (
, .)
,
,
, .
, .
.
, location
( new):
ScreenPosition location;
location.X = 40; // , location
//
, , -
X , , -
. -
, , . ,
,
.
.
, 401
ref- out-
( ).
, -
, ,
:
MyMethod(ref location.X); //
get
set. ,
.
get set .
set
value.
const:
-
. --
,
, .
. , , -
.
Balance, BankAccount:
class BankAccount
{
private decimal _balance;
...
public decimal Balance
{
get { return this._balance; }
set { this._balance = value; }
}
}
, -
,
. ( ,
, , ,
!) -
402 15
, .
,
BankAccount
Deposit Withdraw:
class BankAccount
{
private decimal _balance;
...
public decimal Balance { get { return this._balance; } }
public void Deposit(decimal amount) { ... }
public bool Withdraw(decimal amount) { ... }
}
13
. , -
. get set ,
get set :
interface IScreenPosition
{
int X { get; set; }
int Y { get; set; }
}
, , -
X Y get set.
struct ScreenPosition : IScreenPosition
{
...
public int X
{
get { ... }
set { ... }
}
public int Y
{
get { ... }
set { ... }
}
...
}
,
,
:
403
. , -
virtual ,
.
, 13.
public virtual
:
struct ScreenPosition : IScreenPosition
{
...
int IScreenPosition.X
{
get { ... }
set { ... }
}
int IScreenPosition.Y
{
get { ... }
set { ... }
}
...
}
13, ,
-
. , ,
Circle Square DrawingShape.
SetLocation SetColor,
404 15
.
DrawingShape ,
.
Visual Studio 2015 Drawing,
\Microsoft Press\VCSBS\Chapter 15\Drawing Using Properties .
DrawingShape.cs.
DrawingShape, 13, ,
, , size
_size, locX locY _x _y:
abstract class DrawingShape
{
protected int _size;
protected int _x = 0, _y = 0;
...
}
IDraw.cs Drawing.
SetLocation:
interface IDraw
{
void SetLocation(int xCoord, int yCoord);
...
}
_x _y
DrawingShape .
. SetLocation
X Y, :
interface IDraw
{
int X { get; set; }
int Y { get; set; }
...
}
DrawingShape SetLocation -
X Y:
public int X
{
get { return this._x; }
set { this._x = value; }
}
405
public int Y
{
get { return this._y; }
set { this._y = value; }
}
DrawingPad.xaml.cs
drawingCanvas_Tapped.
.
. ,
SetLocation .
if
:
if (mySquare is IDraw)
{
IDraw drawSquare = mySquare;
drawSquare.SetLocation((int)mouseLocation.X, (int)mouseLocation.Y);
drawSquare.Draw(drawingCanvas);
}
, X Y Square,
:
if (mySquare is IDraw)
{
IDraw drawSquare = mySquare;
drawSquare.X = (int)mouseLocation.X;
drawSquare.Y = (int)mouseLocation.Y;
drawSquare.Draw(drawingCanvas);
}
drawingCanvas_RightTapped.
.
.
, SetLocation
Circle, X Y,
:
if (myCircle is IDraw)
{
IDraw drawCircle = myCircle;
drawCircle.X = (int)mouseLocation.X;
drawCircle.Y = (int)mouseLocation.Y;
drawCircle.Draw(drawingCanvas);
}
IColor.cs.
SetColor:
406 15
interface IColor
{
void SetColor(Color color);
}
Color:
interface IColor
{
Color Color { set; }
}
set, get.
, DrawingShape -
,
, , .
,
( Color).
DrawingShape. SetColor
Color:
public Color Color
{
set
{
if (this.shape != null)
{
SolidColorBrush brush = new SolidColorBrush(value);
this.shape.Fill = brush;
}
}
}
set , -
SetColor, , ,
SolidColorBrush, value.
DrawingPad.xaml.cs.
drawingCanvas_Tapped , Square-,
, :
if (mySquare is IColor)
{
IColor colorSquare = mySquare;
colorSquare.Color = Colors.BlueViolet;
}
407
, Circle-
drawingCanvas_RightTapped:
if (myCircle is IColor)
{
IColor colorCircle = myCircle;
colorCircle.Color = Colors.HotPink;
}
,
.
, , . -
,
.
(.15.1).
. 15.1
, ,
. ,
, get set
,
,
.
, ,
.
.
.
,
, ,
. C#
, ,
, C# .
, (,
- - -
),
. -
, .
, , ,
, .
. ,
, ,
,
.
.
C# ,
.
C# :
class Circle
{
public int Radius{ get; set; }
...
}
Circle Radius. -
, , ,
get set . C#
, :
409
class Circle
{
private int _radius;
public int Radius{
get
{
return this._radius;
}
set
{
this._radius = value;
}
}
...
}
, ,
, ,
, ,
.
. -
,
, private, public protected.
, ,
, set:
class Circle
{
public DateTime CircleCreatedDate { get; }
...
}
, , -
. ,
, , , ,
.
,
, . C#
,
, .
:
class Circle
{
public Circle()
410 15
{
CircleCreatedDate = DateTime.Now;
}
:
class Circle
{
public DateTime CircleCreatedDate { get; } = DateTime.Now;
...
}
,
, -
, , ,
, !
.
get -
.
7 .
,
.
, , :
public class Triangle
{
private int side1Length;
private int side2Length;
private int side3Length;
//
public Triangle()
{
this.side1Length = this.side2Length = this.side3Length = 10;
}
// side1Length
public Triangle(int length1)
{
411
this.side1Length = length1;
this.side2Length = this.side3Length = 10;
}
// side1Length side2Length,
// side3Length
public Triangle(int length1, int length2)
{
this.side1Length = length1;
this.side2Length = length2;
this.side3Length = 10;
}
//
public Triangle(int length1, int length2, int length3)
{
this.side1Length = length1;
this.side2Length = length2;
this.side3Length = length3;
}
}
, ,
, -
, .
, :
. , Triangle
,
side1Length side3Length, -
int-,
, side1Length side2Length.
Triangle- -
, ,
.
:
public class Triangle
{
private int side1Length = 10;
private int side2Length = 10;
private int side3Length = 10;
, . -
, Triangle-
:
Triangle tri1 = new Triangle { Side3Length = 15 };
Triangle tri2 = new Triangle { Side1Length = 15, Side3Length = 20 };
Triangle tri3 = new Triangle { Side2Length = 12, Side3Length = 17 };
Triangle tri4 = new Triangle { Side1Length = 9, Side2Length = 12,
Side3Length = 15 };
. -
C# ,
, set
. -
-
. , Triangle ,
, ,
:
Triangle tri5 = new Triangle("Equilateral triangle") { Side1Length = 3,
Side2Length = 3,
Side3Length = 3 };
, , -
. ,
,
.
,
, -
.
,
.
-
, , , -
, .
413
Visual Studio 2015 AutomaticProperties,
\Microsoft Press\VCSBS\Chapter 15\AutomaticProperties .
AutomaticProperties Program.cs,
Program Main doWork,
.
AutomaticProperties, , ,
AutomaticProperties.
Polygon.cs .
Polygon.cs, Polygon, -
.
Polygon NumSides
SideLength, :
class Polygon
{
public int NumSides { get; set; }
public double SideLength { get; set; }
}
Polygon ,
:
class Polygon
{
...
public Polygon()
{
this.NumSides = 4;
this.SideLength = 10.0;
}
}
NumSides
SideLength.
10 .
Program.cs. doWork -
, , //TODO::
static void doWork()
{
Polygon square = new Polygon();
Polygon triangle = new Polygon { NumSides = 3 };
Polygon pentagon = new Polygon { SideLength = 15.5, NumSides = 5 };
}
414 15
Polygon-. square
. triangle pentagon
,
, Polygon.
triangle NumSides 3,
SideLength 10.0.
pentagon SideLength NumSides.
doWork , :
static void doWork()
{
...
Console.WriteLine($"Square: number of sides is {square.NumSides}, length of
each side is {square.SideLength}");
Console.WriteLine($"Triangle: number of sides is {triangle.NumSides},
length of each side is {triangle.SideLength}");
Console.WriteLine($"Pentagon: number of sides is {pentagon.NumSides},
length of each side is {pentagon.SideLength}");
}
NumSides
SideLength Polygon.
. ,
-
.15.2 .
. 15.2
, Visual
Studio 2015.
, , -
, .
, -
.
415
,
Visual Studio 2015 16 .
Visual Studio 2015,
. ,
.
- , , get
, set, :
struct ScreenPosition
{
...
public int X
{
get { ... }
set { ... }
}
...
}
- ,
, get, :
struct ScreenPosition
{
...
public int X
{
get { ... }
}
...
}
- ,
, set, :
struct ScreenPosition
{
...
public int X
{
set { ... }
}
...
}
416 15
, get
set , :
interface IScreenPosition
{
int X { get; set; } //
int Y { get; set; } //
}
, -
, , :
struct ScreenPosition : IScreenPosition
{
public int X
{
get { ... }
set { ... }
}
public int Y
{
get { ... }
set { ... }
}
}
- -
get set, :
class Polygon
{
public int NumSides { get; set; }
}
, ,
-
, , :
class Circle
{
public DateTime CircleCreatedDate
{ get; } = DateTime.Now;
...
}
, -
, -
, :
Triangle tri3 =
new Triangle { Side2Length = 12,
Side3Length = 17 };
16
, :
,
;
, -
get;
,
set;
, ;
, -
.
15
. -
, .
, ,
.
?
,
. -
, .
, .
, , .
, .
418 16
.
, , , int-.
int- .
int- 32 ,
0, 1. -
, int-
, . -
int-
int int-
. C ,
, , , .
int-
. , -
, , ,
. int 32,
, .
, (true), ,
(false), int- .
C# ,
int- . -
:
(~). , -
. , 8- 11001100 ( -
204) ~,
00110011 ( 51)
, ;
-
8 . C# int- 32 ,
C# -
32- , , -
. , 32 204
00000000000000000000000011001100, C# ~204
11111111111111111111111100110011 (
C# 205).
(<<). ,
. 204 << 2 48. (
? 419
204 11001100,
00110000, 48.)
, .
, (>>);
(|). ,
, ,
, . , -
204 | 24 220 (204 11001100, 24 00011000,
220 11011100);
(&). . -
, ,
, .
204 & 24 8 (204 11001100, 24
00011000, 8 00001000);
(^). -
, -
, - ,
. ( ,
.) , 204 ^ 24 212
(11001100 ^ 00011000 11010100).
int-
. ,
(<<) (&), -
,
bits :
(bits & (1 << 5)) != 0
-
, , . ,
, 5 .
, bits 42. -
00101010. 1
00000001, 1 << 5 00100000,
. bits
& (1<<5) 00101010 & 00100000,
00100000, .
bits 65, 01000001,
01000001 & 00100000,
00000000, .
420 16
, ,
6 -
&=, :
bits &= ~(1 << 5)
, 6 ,
(|). -
|=:
bits |= (1 << 5)
, , -
, .
:
, -
, .
, .
int- , .
int-
, , , ,
bits -
( ,
):
bits[5]
true
:
bits[3] = true
C -
true 1, false -
0. , bits[3] = true :
bits 1.
, -
int- ,
.
? 421
, ,
, -
int-.
. IntBits. int-
( ), ,
IntBits
.
IntBits ,
, .
struct IntBits
{
private int bits;
//
}
, -
.
this, ,
,
. IntBits
, :
struct IntBits
{
...
public bool this [ int index ]
{
get
{
return (bits & (1 << index)) != 0;
}
set
{
if (value) // value true, ,
bits |= (1 << index);
else
bits &= ~(1 << index);
}
}
}
422 16
.
: -
, ,
, .
this .
( -
), this.
, , get set.
get set
.
, ,
, . get set
, -
.
,
, -
.
int- -
IntBits , , -
:
int adapted = 126; // 126 01111110
IntBits bits = new IntBits(adapted);
bool peek = bits[6]; // 6;
// true (1)
bits[0] = true; // 0 true (1)
bits[3] = false; // 3 false (0)
// bits 01110111,
119
, .
.
-
, , get
. :
bool peek = bits[6];
? 423
get
bits, index 6.
-
, ,
set , index ,
:
bits[3] = true;
set
bits, index 3. -
, , ( true),
set
value. value , (
bool).
/.
, get, set.
, (^),
6 bits:
bits[6] ^= true;
:
bits[6] = bits[6] ^ true;
-
, get set.
, get
( ) set (
).
,
, . -
.
,
( ),
:
public int this [ string name ] { ... } //
424 16
( , ),
:
public Name this [ PhoneNumber number ] { ... }
public PhoneNumber this [ Name name ] { ... }
ref- out-,
:
IntBits bits; // bits
Method(ref bits[1]); //
,
, ,
, -
.
, Data, :
struct Wrapper
{
private int[] data;
...
public int[] Data
{
get { return this.data; }
set { this.data = value; }
}
}
, :
Wrapper wrap = new Wrapper();
...
int[] myData = wrap.Data;
myData[0]++;
myData[1]++;
. -
, myData ,
data Wrapper. ,
myData, data, myData[0]++ -
, data[0]++.
, get set Data -
Clone, data,
, . (
Clone 8
.) , Clone ,
:
425
struct Wrapper
{
private int[] data;
...
public int[] Data
{
get { return this.data.Clone() as int[]; }
set { this.data = value.Clone() as int[]; }
}
}
.
-
,
:
struct Wrapper
{
private int[] data;
...
public int this [int i]
{
get { return this.data[i]; }
set { this.data[i] = value; }
}
}
,
:
Wrapper wrap = new Wrapper();
...
int[] myData = new int[2];
myData[0] = wrap[0];
myData[1] = wrap[1];
myData[0]++;
myData[1]++;
myData
Wrapper-.
Wrapper-, :
wrap[0]++;
.
get, set ,
426 16
get set .
-
, :
interface IRawInt
{
bool this [ int index ] { get; set; }
}
struct RawInt : IRawInt
{
...
public bool this [ int index ]
{
get { ... }
set { ... }
}
...
}
,
.
get set:
class RawInt : IRawInt
{
...
public virtual bool this [ int index ]
{
get { ... }
set { ... }
}
...
}
, 13 -
.
public (, ,
):
struct RawInt : IRawInt
{
...
bool IRawInt.this [ int index ]
{
get { ... }
set { ... }
}
...
}
Windows 427
Windows
-
. PhoneBook :
, Name ()
PhoneNumber ( ), , ,
PhoneNumber Name. ( Name
PhoneNumber .) -
.
Microsoft Visual Studio Indexers,
\Microsoft Press\VCSBS\Chapter 16\Indexers .
, -
.
.
Name ()
Phone Number ( ). :
,
. -
, Add (),
, ,
. , Add ,
. , .16.1.
.
Visual Studio 2015 .
Name.cs Indexers.
Name. . -
.
Text, .
( Equals GetHashCode
Name-, .)
PhoneNumber.cs PhoneNumber.
Name.
PhoneBook.cs PhoneBook.
428 16
. 16.1
: Name-
names PhoneNumber- phoneNumbers. PhoneBook
Add,
. ,
Add. enlargeIfFull Add
, .
, ,
, .
Add , -
.
PhoneBook , -
. -
.
Windows 429
PhoneBook.cs // TODO: write 1st indexer here,
,
PhoneBook, .
Name-,
PhoneNumber-. get .
:
sealed class PhoneBook
{
...
public Name this[PhoneNumber number]
{
get
{
}
}
...
}
get,
.
,
. IndexOf, -
Array. IndexOf ,
,
. IndexOf -
(phoneNumbers). IndexOf .
IndexOf , ,
1. ,
,
Name-. (, Name , ,
name null.)
sealed class PhoneBook
{
...
public Name this [PhoneNumber number]
{
get
{
int i = Array.IndexOf(this.phoneNumbers, number);
if (i != -1)
{
return this.names[i];
}
else
{
430 16
-
, , , ,
. Name PhoneNumber -
( ),
.
,
, , , ,
.
MainPage.xaml.cs findByNameClick.
Find By Name ( ).
Windows 431
. // TODO:
, . -
:
Tex, name.
, ;
, -
, PhoneBook.
(, MainPage PhoneBook-
phoneBook.) Name-
PhoneBook;
Text,
PhoneNumber, null ,
phoneNumber.
Not Found, -
, .
findByNameClick
:
private void findByNameClick(object sender, RoutedEventArgs e)
{
string text = name.Text;
if (!String.IsNullOrEmpty(text))
{
Name personsName = new Name(text);
PhoneNumber personsPhoneNumber = this.phoneBook[personsName];
phoneNumber.Text = String.IsNullOrEmpty(personsPhoneNumber.Text) ?
"Not Found" : personsPhoneNumber.Text;
}
}
, ,
.
String- IsNullOrEmpty -
, null-.
. true, null -
, false.
, Text phoneNumber ,
? :,
ifelse. : -
,
true -
false.
432 16
String.IsNullOrEmpty(personsPhoneNumber.Text)
true, ,
, Not Found; -
, Text personsPhoneNumber.
? : :
= < > ? <, true> : <,
false>
MainPage.xaml.cs findByPhoneNumberClick, -
findByNameClick. findByPhoneNumberClick
Find By Phone Number ( ).
, // TODO:.
, . ( -
.)
Text
phoneNumber. , , .
, ,
PhoneBook.
name -
Text, Name.
:
private void findByPhoneNumberClick(object sender, RoutedEventArgs e)
{
string text = phoneNumber.Text;
if (!String.IsNullOrEmpty(text))
{
PhoneNumber personsPhoneNumber = new PhoneNumber(text);
Name personsName = this.phoneBook[personsPhoneNumber];
name.Text = String.IsNullOrEmpty(personsName.Text) ?
"Not Found" : personsName.Text;
}
}
-
.
. -
,
Add () (
). Add ()
433
Add ,
.
, -
. ,
.
, .
Name Find
By Name ( ).
Phone Number ,
.
Phone Number ,
Find By Phone Number ( ). -
Name .
Name , ,
Find By Name ( ).
Phone Number ,
, Not Found.
Visual Studio 2015.
, ,
, .
, -
,
get, , set,
, .
, -
Visual Studio 2015 17 .
Visual Studio 2015, -
.
, .
434 16
- , this,
-
. get
/ set, :
struct RawInt
{
...
public bool this [ int index ]
{
get { ... }
set { ... }
}
...
}
get / set, :
- interface IRawInt
{
bool this [ int index ] { get; set; }
}
- , , -
- , :
struct RawInt : IRawInt
{
...
public bool this [ int index ]
{
get { ... }
set { ... }
}
...
}
, -
, , , :
struct RawInt : IRawInt
, {
- ...
- bool IRawInt.this [ int index ]
{
get { ... }
set { ... }
}
...
}
17
, :
;
, -
;
- ,
;
;
, ,
, .
8 ,
object .
,
,
object.
object -
.
, . -
, .
, ,
.
, object
, , ,
. , -
,
. :
436 17
class Queue
{
private const int DEFAULTQUEUESIZE = 100;
private int[] data;
private int head = 0, tail = 0;
private int numElements = 0;
public Queue()
{
this.data = new int[DEFAULTQUEUESIZE];
}
this.data[this.head] = item;
this.head++;
this.head %= this.data.Length;
this.numElements++;
}
. .
, object 437
, Enqueue, -
Dequeue. head tail ,
.
numElements , .
Enqueue Dequeue ,
,
. ,
Queue- . ,
, :
Queue queue = new Queue(); // Queue-
queue.Enqueue(100);
queue.Enqueue(-25);
queue.Enqueue(33);
Console.WriteLine($"{queue.Dequeue()}"); // 100
Console.WriteLine($"{queue.Dequeue()}"); // -25
Console.WriteLine($"{queue.Dequeue()}"); // 33
Queue int-, ,
, ,
, Circle (. 7 -
), Horse Whale (. 12 -
)? , Queue
,
Horse- :
,
Queue object,
Enqueue Dequeue ,
object :
class Queue
{
...
private object[] data;
...
public Queue()
{
this.data = new object[DEFAULTQUEUESIZE];
}
...
this.data = new object[size];
...
}
,
object.
( , ) System.Object Microsoft
.NET Framework ( C# object System.Object). , -
Enqueue Dequeue ,
Circles, Horses, Whales , -
. , Dequeue
,
object:
Queue queue = new Queue();
Horse myHorse = new Horse();
queue.Enqueue(myHorse); // , Horse
...
Horse dequeuedHorse = (Horse)queue.Dequeue(); // object
// Horse
,
,
object Horse. -
object . ,
, :
Queue queue = new Queue();
Horse myHorse = new Horse();
queue.Enqueue(myHorse);
...
Circle myCircle = (Circle)queue.Dequeue(); //
,
System.
, 439
InvalidCastException.
Horse Circle-,
. ,
,
.
, , .
object
,
.
,
:
Queue queue = new Queue();
int myInt = 99;
queue.Enqueue(myInt); // int object
...
myInt = (int)queue.Dequeue(); // object int
Queue ,
object, . , -
, int-,
.
int-
, (
8).
- ,
, -
.
,
, , .
,
, C#
,
, , -
, . C# ,
, , :
class Queue<T>
{
...
}
440 17
T
, .
- Queue ,
T (Circle, Horse, int ..).
:
class Queue<T>
{
...
private T[] data; // 'T', 'T'
...
public Queue()
{
this.data = new T[DEFAULTQUEUESIZE]; // 'T'
//
}
T C#
, T.
, Queue-.
Queue- int- Queue- Horse-:
Queue<int> intQueue = new Queue<int>();
Queue<Horse> horseQueue = new Queue<Horse>();
, -
.
Dequeue,
:
, 441
intQueue.Enqueue(99);
int myInt = intQueue.Dequeue(); //
Horse myHorse = intQueue.Dequeue(); // :
// 'int' 'Horse'
//
, T
.
, T
. :
struct Person
{
...
}
...
Queue<int> intQueue = new Queue<int>();
Queue<Person> personQueue = new Queue<Person>();
,
Person-. -
Enqueue Dequeue. intQueue :
public void Enqueue(int item);
public int Dequeue();
personQueue :
public void Enqueue(Person item);
public Person Dequeue();
Queue, object. , -
-, item Enqueue
, , .
, Dequeue, ,
.
.
System.Collections.Generic
.NET Framework Queue,
, . -
, 18
.
. , ,
(, , - ):
Queue<Queue<int>> queueQueue = new Queue<Queue<int>>();
442 17
- . , -
Dictionary,
System.Collections.Generic .NET Framework,
: ,
( 18).
,
, , .
-
-, , -
, ,
. ,
Queue, object,
. , -
object, object.
, ,
object- object-.
Queue<T>.
(, Queue<int> Queue<Horse>)
-
, -. , Queue<int>
Queue<Horse>,
. -
,
. --
(Queue<int>, Queue<Horse> ..) -
,
( ,
).
, , --
, , . -
, PrintableCollection (,
), , ,
- 443
, Print. , -
.
, -
, ,
, . ,
IPrintable Print, -
PrintableCollection:
-
, , , T,
IPrintable. ,
.
-
System.Collections.Generic .NET
Framework -.
-, -
. ,
.
, -
,
, ,
.
,
.
, .
(Donald
E. Knuth) , 3 (-
Addison-Wesley Professional 1998 ,
). ,
.
() ,
:
444 17
(datum), , , -
.
, .
,
. .
.17.1.
. 17.1
. -
, ,
. I -
B:
"B" ,
"B" "I"
"N" "B"
"N" , "I",
"B" ,
"B" "I"
"I" "B"
- 445
"B"
"B" "I"
"I" "B"
, -
.
. -
, ,
.
-
.
-
, -
,
.
, , .17.2.
. -
:
.17.3. -
,
.
446 17
: 1, 5, -2, 1, 6 : 5, -2, 1, 6
()
: -2, 1, 6 : 1, 5, -2, 1, 6
: 6 :
. 17.2
, . -
,
.
- 447
: -2 : -2, 1
: -2, 1, 1 : -2, 1, 1, 5
: -2, 1, 1, 5, 6
. 17.3
-
. ,
.
- ,
.
( , ),
. ,
.dll.
448 17
using.
.
SYSTEM.ICOMPARABLE SYSTEM.ICOMPARABLE<T>
. -
, int, <, >
==. , - ,
Mammal Circle, ?
,
( , ) -
, IComparable.
CompareTo, , , -
, ,
.
Circle,
7. :
class Circle
{
public Circle(int initialRadius)
{
radius = initialRadius;
}
, System.
IComparable CompareTo. CompareTo
Circle- .
:
- 449
return -1;
}
}
System.IComparable, ,
object. -
. , , , , -
CompareTo - Circle.
System.IComparable Area
. Circle
- , . System
- IComparable<T>, -
:
int CompareTo(T other);
, object,
(T) ,
. , -
Circle:
class Circle : System.IComparable<Circle>
{
...
public int CompareTo(Circle other)
{
if (this.Area() == other.Area())
return 0;
if (this.Area() > other.Area())
return 1;
return -1;
}
}
CompareTo , -
IComparable<Circle>. -
System.IComparable<T>, System.IComparable.
,
.NET Framework.
450 17
Tree<TItem>
Microsoft Visual Studio 2015
.
Visual C#. -
. BinaryTree.
\Microsoft Press\VCSBS\Chapter 17
, OK.
Class Library, , -
.
, , -
, (
), .
Class1.cs,
, Tree.cs.
Visual Studio ,
.
Tree Tree<TItem>,
:
public class Tree<TItem>
{
}
Tree<TItem> ,
, TItem , -
- IComparable<TItem>.
. -
Tree<TItem> :
public class Tree<TItem> where TItem : IComparable<TItem>
{
}
Tree<TItem>
: TItem- NodeData Tree<TItem>-
LeftTree RightTree, :
Tree<TItem> ,
TItem- nodeValue.
NodeData nodeValue LeftTree RightTree
null-,
:
public class Tree<TItem> where TItem : IComparable<TItem>
{
...
public Tree(TItem nodeValue)
{
this.NodeData = nodeValue;
this.LeftTree = null;
this.RightTree = null;
}
}
, -
: Tree, Tree<TItem>.
Tree<TItem> Insert,
. TItem-
.
:
public class Tree<TItem> where TItem: IComparable<TItem>
{
...
public void Insert(TItem newItem)
{
}
}
Insert
.
, Insert , .
, .
, ,
Insert :
...
"N" "B"
"N" "I"
"B"
"B" "I" ,
452 17
"I" "B"
...
Insert ,
TItem currentNodeValue. ,
, NodeData,
:
public void Insert(TItem newItem)
{
TItem currentNodeValue = this.NodeData;
}
Insert
if-else,
currentNodeValue. CompareTo,
IComparable<T>, ,
, :
public void Insert(TItem newItem)
{
TItem currentNodeValue = this.NodeData;
if (currentNodeValue.CompareTo(newItem) > 0)
{
//
}
else
{
//
}
}
if //
:
if (this.LeftTree == null)
{
this.LeftTree = new Tree<TItem>(newItem);
}
else
{
this.LeftTree.Insert(newItem);
}
. ,
, -
,
Insert.
- 453
else if-else
// -
, :
if (this.RightTree == null)
{
this.RightTree = new Tree<TItem>(newItem);
}
else
{
this.RightTree.Insert(newItem);
}
Tree<TItem> Insert
WalkTree. ,
, ,
. :
public string WalkTree()
{
}
WalkTree ,
. ,
.
:
public string WalkTree()
{
string result = "";
if (this.LeftTree != null)
{
result = this.LeftTree.WalkTree();
}
if (this.RightTree != null)
{
result += this.RightTree.WalkTree();
}
return result;
}
.
,
.
Tree<TItem>
.
454 17
Tree<TItem>
BinaryTree,
.
BinaryTree,
BinaryTree.
, . -
BinaryTreeTest. \Microsoft
Press\VCSBS\Chapter 17 , OK.
BinaryTreeTest,
(Set As Startup
Project). BinaryTreeTest. -
.
BinaryTreeTest,
, .
BinaryTreeTest (.17.4), .
BinaryTree, ,
OK.
BinaryTreeTest
BinaryTree.
BinaryTreeTest, BinaryTree, -
. BinaryTreeTest
Tree<TItem>.
-
, , (
.dll), .
.
.
, Program,
Program.cs, using,
:
using BinaryTree;
- 455
. 17.4
Main ,
:
static void Main(string[] args)
{
Tree<int> tree1 = new Tree<int>(10);
tree1.Insert(5);
tree1.Insert(11);
tree1.Insert(5);
tree1.Insert(-12);
tree1.Insert(15);
tree1.Insert(0);
tree1.Insert(14);
tree1.Insert(-8);
tree1.Insert(10);
tree1.Insert(8);
tree1.Insert(8);
-
. , 10.
Insert , WalkTree ,
456 17
,
.
, int C#
System.Int32: int-,
System.Int32. System.Int32
IComparable IComparable<T>,
Tree<int>-. string
System.String, IComparable IComparable<T>.
,
. .
. , -
:
12 8 0 5 5 8 8 10 10 11 14 15
sortedData = tree2.WalkTree();
Console.WriteLine($"Sorted data is: {sortedData}");
}
, -
.
.
,
. .
- 457
. ,
, ,
(.17.5):
! Are Are Feeling Hello Hope How I Today Well World You You
. 17.5
-
- --
.
- -
, ,
, -.
-, , -
( ).
- --
. ,
, ,
.
-
, - (
). , - Swap<T>, -
,
.
, -:
static void Swap<T>(ref T first, ref T second)
{
T temp = first;
first = second;
second = temp;
}
458 17
. -
, Swap<T>
:
int a = 1, b = 2;
Swap<int>(ref a, ref b);
...
string s1 = "Hello", s2 = "World";
Swap<string>(ref s1, ref s2);
- -
, -
Swap<T>
. Swap<int>
Swap<string>, -, -
, .
- -
. Tree<TItem>
Insert. -
, Insert .
- InsertIntoTree,
,
.
.
InsertIntoTree
Visual Studio 2015 ,
. Co
BuildTree. \Microsoft Press\
VCSBS\Chapter 17 .
, OK.
.
BuildTree (
, ).
,
\Microsoft Press\VCSBS\Chapter 17\BinaryTree\BinaryTree\bin\Debug
, BinaryTree.dll,
.
- 459
BinaryTree.dll
BuildTree , ,
OK. BinaryTree
, .
, Program.cs,
using:
using BinaryTree;
, Tree<TItem> -
.
Main Program InsertIntoTree.
(static void),
Tree<TItem> params- TItem data.
tree , , -
.
:
static void InsertIntoTree<TItem>(ref Tree<TItem> tree,
params TItem[] data)
{
}
TItem, , ,
IComparable<TItem>.
InsertIntoTree, where,
:
static void InsertIntoTree<TItem>(ref Tree<TItem> tree,
params TItem[] data) where TItem :IComparable<TItem>
{
}
InsertIntoTree , -
.
params, Insert.
tree null,
Tree<TItem> tree :
static void InsertIntoTree<TItem>(ref Tree<TItem> tree,
params TItem[] data) where TItem : IComparable<TItem>
{
foreach (TItem datum in data)
{
if (tree == null)
460 17
{
tree = new Tree<TItem>(datum);
}
else
{
tree.Insert(datum);
}
}
}
InsertIntoTree
Main Program ,
, Tree -
,
InsertIntoTree, ,
WalkTree Tree:
,
. .
.
:
A M M N X Z Z
-
8 , object
. ,
:
string myString = "Hello";
object myObject = myString;
, String
Object, , .
- 461
, -
:
interface IWrapper<T>
{
void SetData(T data);
T GetData();
}
class Wrapper<T> : IWrapper<T>
{
private T storedData;
T IWrapper<T>.GetData()
{
return this.storedData;
}
}
Wrapper<T> .
IWrapper SetData,
Wrapper<T> , GetData, -
Wrapper<T> .
:
Wrapper<string> stringWrapper = new Wrapper<string>();
IWrapper<string> storedStringWrapper = stringWrapper;
storedStringWrapper.SetData("Hello");
Console.WriteLine($"Stored value is {storedStringWrapper.GetData()}");
Wrapper<string>. SetData,
IWrapper<string>. ( Wrapper<T>
,
.) -
IWrapper<string> GetData. ,
Stored value is Hello (
Hello).
:
IWrapper<object> storedObjectWrapper = stringWrapper;
,
IWrapper<string> , ,
object, string. ?
462 17
, ( , -
, ), -
, .
, , Cannot
implicitly convert type Wrapper<string> to IWrapper<object> (
Wrapper<string> IWrapper<object>
).
:
IWrapper<object> storedObjectWrapper = (IWrapper<object>)stringWrapper;
,
InvalidCastException.
, , -
. ,
,
Circle- :
IWrapper<object> storedObjectWrapper = (IWrapper<object>)stringWrapper;
Circle myCircle = new Circle();
storedObjectWrapper.SetData(myCircle);
IWrapper<T> ().
IWrapper<A> IWrapper<B>,
A B. C#
, .
, IWrapper<T>
IStoreWrapper<T> IRetrieveWrapper<T>, ,
Wrapper<T> :
interface IStoreWrapper<T>
{
void SetData(T data);
}
interface IRetrieveWrapper<T>
{
T GetData();
}
T IRetrieveWrapper<T>.GetData()
{
return this.storedData;
}
}
Wrapper<T> , , -
, SetData GetData
:
Wrapper<string> stringWrapper = new Wrapper<string>();
IStoreWrapper<string> storedStringWrapper = stringWrapper;
storedStringWrapper.SetData("Hello");
IRetrieveWrapper<string> retrievedStringWrapper = stringWrapper;
Console.WriteLine($"Stored value is {retrievedStringWrapper.GetData()}");
?
IRetrieveWrapper<object> retrievedObjectWrapper = stringWrapper;
, ,
, . , ,
C#
, .
IRetrieveWrapper<T> GetData
, Wrapper<T>-, - -
. , -
,
,
-
.
out:
interface IRetrieveWrapper<out T>
{
T GetData();
}
. -
A B , A
B, IRetrieveWrapper<A>-
IRetrieveWrapper<B>-.
:
464 17
// string object,
//
IRetrieveWrapper<object> retrievedObjectWrapper = stringWrapper;
out ,
.
,
out .
. ,
. , -
, int :
Wrapper<int> intWrapper = new Wrapper<int>();
IStoreWrapper<int> storedIntWrapper = intWrapper; //
...
//
IRetrieveWrapper<object> retrievedObjectWrapper = intWrapper;
, .NET
Framework, IEnumerable<T>, -
19 .
( 18). - out -
.
, , -
, ,
- B
A , B A. -
,
.NET Framework.
System.Collections.Generic .NET
IComparer, :
public interface IComparer<in T>
{
int Compare(T x, T y);
}
, , Compare,
, -
T. , Compare
- 465
: , x y ,
, x y, , -
x y. ,
-. ( GetHashCode
Object. , -
.
.)
class ObjectComparer : IComparer<Object>
{
int IComparer<Object>.Compare(Object x, Object y)
{
int xHash = x.GetHashCode();
int yHash = y.GetHashCode();
if (xHash == yHash)
return 0;
if (xHash < yHash)
return -1;
return 1;
}
}
ObjectComparer-
IComparer<Object> Compare:
Object x = ...;
Object y = ...;
ObjectComparer objectComparer = new ObjectComparer();
IComparer<Object> objectComparator = objectComparer;
int result = objectComparator.Compare(x, y);
. ,
IComparer-,
, :
IComparer<String> stringComparator = objectComparer;
-
, .
, IComparer<T>,
. Compare
. Objects,
, , Strings,
Objects. ,
String , Object,
.
466 17
- . C#
, -
, Compare,
, ,
? IComparer,
, in:
public interface IComparer<in T>
{
int Compare(T x, T y);
}
in C#,
T, ,
T. T ,
. ,
-, , -
, , .
, A , ,
B A,
( - -
), . ,
B A.
-
, .
, - List<T> ( -
System.Collections.Generic) Sort
BinarySearch IComparer<T>. List<Object>
, Sort BinarySearch
. -
Sort BinarySearch ,
,
,
. , , ,
. -
, , ,
.
. - -
, . (
.)
. -
,
467
. ( -
, ,
, .)
, -
. - -
in .
,
. ,
. ,
- -. , -
-,
.
,
Visual Studio 2015 18.
Visual Studio 2015,
. ,
.
-
, :
Queue<int> myQueue = new Queue<int>();
, , :
public class Tree<TItem>
{
...
}
, where, :
- public class Tree<TItem>
where TItem : IComparable<TItem>
{
...
}
468 17
--
, :
static void InsertIntoTree<TItem>
(Tree<TItem> tree, params TItem[] data)
{
...
}
- ,
:
InsertIntoTree<char>(charTree, 'Z', 'X');
-
out.
,
, -
:
interface IRetrieveWrapper<out T>
{
T GetData();
}
- -
in. -
,
:
public interface IComparer<in T>
{
int Compare(T x, T y);
}
18
, :
, -
, .NET Framework;
;
;
, , -
;
.
10 , -
. , ,
, . -
, ,
,
- . ,
.
- -
, , , -
, 17
, .
.
?
Microsoft .NET ,
,
.
470 18
17 , System.
Collections.Generic.
, -
: , -
,
.
, -
, .
, Stack<T>
,
Push Pop.
Pop
. Queue<T> Enqueue
Dequeue, 17. Enqueue -
, Dequeue ,
.
, .18.1.
18.1
List<T> , , ,
,
Queue<T> ,
,
,
Stack<T> , -
,
,
, ,
LinkedList<T> ,
.
, , -
,
HashSet<T> , -
.
, -
HashSet<T>-, -
HashSet<T>-
? 471
18.1 ()
Dictionary<TKey, , -
TValue> ,
SortedList<TKey, .
TValue> IComparable<T>-
.
.NET Framework.
List<T>
- List<T> .
, , -
List<T>
,
.
List<T> ,
,
.
472 18
, ( ,
),
, .
. ,
.
, .
!
List<T> ,
.
List<T> .
.
,
.
, List<T> .
List<T> -
Remove . List<T>
, . RemoveAt
, List<T>.
List<T>,
Add,
. List<T> .
List<T>,
Insert. List<T> -
.
List<T>-,
Sort.
,
List<T> foreach, -
. ,
foreach, List<T>,
Remove, Add Insert -
InvalidOperationException.
, , -
List<int>,
:
? 473
using System;
using System.Collections.Generic;
...
List<int> numbers = new List<int>();
// List<int> Add
foreach (int number in new int[12]{10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1})
{
numbers.Add(number);
}
//
//
// ,
numbers.Insert(numbers.Count-1, 99);
// , 7 (4- 3)
numbers.Remove(3);
// , 7- 6 (10)
numbers.RemoveAt(6);
// 11 for
Console.WriteLine("Iterating using a for statement:");
for (int i = 0; i < numbers.Count; i++)
{
int number = numbers[i]; //
// ,
Console.WriteLine(number);
}
// 11 foreach
Console.WriteLine("\nIterating using a foreach statement:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
, :
Iterating using a for statement:
10
9
8
7
6
5
4
3
2
99
1
Iterating using a foreach statement:
10
9
8
474 18
7
6
5
4
3
2
99
1
List<T>
. -
List<T> Count,
Length.
LinkedList<T>
LinkedList<T> . -
-
( Next) ( Previous).
Previous null,
Next , .
List<T>, LinkedList<T> -
, , .
AddFirst
Previous -
.
AddLast,
Next
.
( ) -
AddBefore AddAfter.
LinkedList<T> ,
First, Last .
Next
Previous, ,
null.
foreach,
LinkedList<T>-, .
LinkedList<T>
Remove, RemoveFirst RemoveLast.
? 475
LinkedList<T>.
, , -
for, Next
Previous, null,
:
using System;
using System.Collections.Generic;
...
LinkedList<int> numbers = new LinkedList<int>();
// List<int> AddFirst
foreach (int number in new int[] { 10, 8, 6, 4, 2 })
{
numbers.AddFirst(number);
}
// for
Console.WriteLine("Iterating using a for statement:");
for (LinkedListNode<int> node = numbers.First; node != null; node = node.Next)
{
int number = node.Value;
Console.WriteLine(number);
}
// foreach
Console.WriteLine("\nIterating using a foreach statement:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
//
Console.WriteLine("\nIterating list in reverse order:");
for (LinkedListNode<int> node = numbers.Last; node != null; node = node.Previous)
{
int number = node.Value;
Console.WriteLine(number);
}
, :
Iterating using a for statement:
2
4
6
8
10
Iterating using a foreach statement:
2
4
6
8
10
476 18
Queue<T>
Queue<T> .
( Enqueue)
( Dequeue).
Queue<int>- -
:
using System;
using System.Collections.Generic;
...
Queue<int> numbers = new Queue<int>();
//
Console.WriteLine("Populating the queue:");
foreach (int number in new int[4]{9, 3, 7, 2})
{
numbers.Enqueue(number);
Console.WriteLine($"{number} has joined the queue");
}
//
Console.WriteLine("\nThe queue contains the following items:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
//
Console.WriteLine("\nDraining the queue:");
while (numbers.Count > 0)
{
int number = numbers.Dequeue();
Console.WriteLine($"{number} has left the queue");
}
, :
Populating the queue:
9 has joined the queue
3 has joined the queue
7 has joined the queue
2 has joined the queue
The queue contains the following items:
9
3
? 477
7
2
Draining the queue:
9 has left the queue
3 has left the queue
7 has left the queue
2 has left the queue
Stack<T>
Stack<T> .
( pop).
: -
, .
( , ,
, !)
, , foreach
:
using System;
using System.Collections.Generic;
...
Stack<int> numbers = new Stack<int>();
//
Console.WriteLine("Pushing items onto 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");
}
//
Console.WriteLine("\nThe stack now contains:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
//
Console.WriteLine("\nPopping items from the stack:");
while (numbers.Count > 0)
{
int number = numbers.Pop();
Console.WriteLine($"{number} has been popped off the stack");
}
, :
Pushing items onto the stack:
9 has been pushed on the stack
478 18
Dictionary<TKey, TValue>
List<T>
. -
(, [4]), 4,
. ,
, , string,
double Time. -
.
Dictionary<TKey, TValue>
, ,
.
Dictionary<TKey, TValue> ,
, -
, .
Dictionary<TKey, TValue> .
Dictionary<TKey, TValue> -
.
Add , .
-
( ),
, :
.
Dictionary<TKey, TValue>
ContainsKey.
Dictionary<TKey, TValue>
, ,
. -
Dictionary<TKey, TValue>
.
? 479
Dictionary<TKey,
TValue> foreach, KeyValue
Pair<TKey, TValue>. ,
, Dictionary<TKey, TValue>,
Key Value. -
,
Dictionary<TKey, TValue>.
, -
, :
using System;
using System.Collections.Generic;
...
Dictionary<string, int> ages = new Dictionary<string, int>();
// Dictionary
ages.Add("John", 51); // Add
ages.Add("Diana", 50);
ages["James"] = 23; // ,
ages["Francesca"] = 21;
// foreach,
// KeyValuePair
Console.WriteLine("The Dictionary contains:");
foreach (KeyValuePair<string, int> element in ages)
{
string name = element.Key;
int age = element.Value;
Console.WriteLine($"Name: {name}, Age: {age}");
}
:
The Dictionary contains:
Name: John, Age: 51
Name: Diana, Age: 50
Name: James, Age: 23
Name: Francesca, Age: 21
System.Collections.Generic
SortedDictionary<TKey, TValue>. -
, .
SortedList<TKey, TValue>
SortedList<TKey, TValue> Dictionary<TKey, TValue>
, .
, -
, SortedList.
480 18
SortedList<TKey, TValue>
, SortedDictionary<TKey, TValue>,
( ),
SortedList<TKey, TValue> .
SortedList<TKey, TValue> ,
, -
.
. SortedList<TKey, TValue> -
. ,
SortedList<TKey, TValue> -
.
Dictionary<TKey, TValue>, SortedList<TKey, TValue>
.
SortedList<TKey, TValue> -
foreach, KeyValuePair<TKey, TValue>.
KeyValuePair<TKey, TValue>
Key.
,
, ,
Dictionary<TKey, TValue>
SortedList<TKey, TValue>:
using System;
using System.Collections.Generic;
...
SortedList<string, int> ages = new SortedList<string, int>();
// SortedList
ages.Add("John", 51); // Add
ages.Add("Diana", 50);
ages["James"] = 23; // ,
ages["Francesca"] = 21;
// foreach,
// KeyValuePair
Console.WriteLine("The SortedList contains: ");
foreach (KeyValuePair<string, int> element in ages)
{
string name = element.Key;
int age = element.Value;
Console.WriteLine($"Name: {name}, Age: {age}");
}
, , -
:
? 481
HashSet<T>
HashSet<T> ,
-
.
HashSet<T> Add, -
Remove.
HashSet<T> IntersectWith, UnionWith
ExceptWith. HashSet<T>,
, ,
, , ,
HashSet<T>-. -
, HashSet<T>-
. ,
HashSet<T>-
, IsSubsetOf, IsSupersetOf,
IsProperSubsetOf IsProperSupersetOf.
.
HashSet<T>- -, -
.
HashSet<T>- .
, HashSet<T>-,
IntersectWith ,
:
using System;
using System.Collections.Generic;
...
HashSet<string> employees = new HashSet<string>(new string[]
{"Fred","Bert","Harry","John"});
HashSet<string> customers = new HashSet<string>(new string[]
{"John","Sid","Harry","Diana"});
employees.Add("James");
customers.Add("Francesca");
Console.WriteLine("Employees:");
foreach (string name in employees)
{
482 18
Console.WriteLine(name);
}
Console.WriteLine("\nCustomers:");
foreach (string name in customers)
{
Console.WriteLine(name);
}
:
Employees:
Fred
Bert
Harry
John
James
Customers:
John
Sid
Harry
Diana
Francesca
Customers who are also employees:
John
Harry
System.Collections.Generic
SortedSet<T>,
HashSet<T>. , , ,
. SortedSet<T> HashSet<T>
, , ,
SortedSet<T> HashSet<T>.
, -
(Add List<T>, Enqueue
Queue<T>, Push Stack<T> ..)
.
, , ,
Find, - 483
. , -
List<int>- numbers, -
Add:
List<int> numbers = new List<int>(){10, 9, 8, 7, 7, 6, 5, 10, 4, 3, 2, 1};
C# -
Add. ,
, Add. ( Stack<T> Queue<T>
.)
, , -
Dictionary<TKey, TValue>,
, :
Dictionary<string, int> ages = new Dictionary<string, int>()
{
["John"] = 51,
["Diana"] = 50,
["James"] = 23,
["Francesca"] = 21
};
:
Dictionary<string, int> ages = new Dictionary<string, int>()
{
{"John", 51},
{"Diana", 50},
{"James", 23},
{"Francesca", 21}
};
,
.
, ,
, .
Find, -
- Dictionary<TKey, TValue>,
SortedDictionary<TKey, TValue> SortedList<TKey, TValue>,
, , , -
, ,
. ,
484 18
, List<T> LinkedList<T>,
, , ,
Find.
Find ,
. ,
, , -
. Find,
,
. , List<T> LinkedList<T>
, FindLast, -
, List<T> FindAll, -
List<T>, ,
.
-
-. , .
, C#
.
, Haskell, , , -
. , : -
,
, .
Haskell, -, ,
http://www.haskell.org/haskellwiki/Haskell.
3 ,
: ,
, . -
: . -
, ( ) -
, -. -
Find
:
true false.
Find ( ) List<Person>,
Person . Find ,
ID 3:
struct Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
Find, - 485
}
...
//
List<Person> personnel = new List<Person>()
{
new Person() { ID = 1, Name = "John", Age = 51 },
new Person() { ID = 2, Name = "Sid", Age = 28 },
new Person() { ID = 3, Name = "Fred", Age = 34 },
new Person() { ID = 4, Name = "Paul", Age = 22 },
};
// , ID 3
Person match = personnel.Find((Person p) => { return p.ID == 3; });
:
ID: 3
Name: Fred
Age: 34
. ,
, , , -
, , .
- ,
.
,
.
3 , =>
, . -
=> . -
, , ,
- ( ) ,
.
486 18
, - , -
, . --
, -
(
). , ,
. ,
,
, -.
Find ,
:
Person match = personnel.Find(p => p.ID == 3);
-
- ,
C#,
. .
-
-,
. ( , -
.) C# -
-,
- . , -
-, C#:
x => x * x // , .
// x .
x => { return x * x ; } // , ,
//
// , C#.
(int x) => x / 2 // , ,
// 2
// x .
() => folder.StopFolding(0) // .
// .
// ,
// .
, -,
.
- ,
=>. ,
C# -.
, -
, ,
ref, .
- ,
.
-
C#, , , -
.
, -,
.
-
, ,
-, .
!
-
- C# 3.0. C# 2.0
, ,
. -
,
, :
this.stopMachinery += delegate { folder.StopFolding(0); };
:
control.Add(delegate { folder.StopFolding(0); } );
, -
delegate. ,
, , ,
delegate:
488 18
- -
, ,
C#, . ,
, --
.
.
.
.
.
. ,
.
.
. ,
List<T> Add Insert,
Find.
,
, ToArray.
. , -
,
.
, 10,
, .
Microsoft Visual Studio 2015 Cards,
\Microsoft Press\VCSBS\Chapter 18\Cards .
489
10,
. PlayingCard ,
, -
.
Pack.cs.
using:
using System.Collections.Generic;
Pack , , -
cardPack Dictionary<Suit,
List<PlayingCard>>:
class Pack
{
...
private Dictionary<Suit, List<PlayingCard>> cardPack;
...
}
. (Dictionary),
, .
Pack. -
, ,
cardPack Dictionary-, :
public Pack()
{
this.cardPack = new Dictionary<Suit, List<PlayingCard>>(NumSuits);
...
}
Dictionary- -
,
,
. ( ,
, - ).
Dictionary-
( ), ,
(NumSuits 4).
for List<PlayingCard>
cardsInSuit, , ,
, CardsPerSuit. -
:
490 18
public Pack()
{
this.cardPack = new Dictionary<Suit, List<PlayingCard>>(NumSuits);
for (Suit = Suit.Clubs; suit <= Suit.Spades; suit++)
{
List<PlayingCard> cardsInSuit = new List<PlayingCard>(CardsPerSuit);
for (Value value = Value.Two; value <= Value.Ace; value++)
{
...
}
}
}
, , for,
, PlayingCard:
for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
{
List<PlayingCard> cardsInSuit = new List<PlayingCard>(CardsPerSuit);
for (Value value = Value.Two; value <= Value.Ace; value++)
{
cardsInSuit.Add(new PlayingCard(suit, value));
}
}
DealCardFromPack.
, .
, ,
,
Dictionary-. , ,
( ) : ,
. Find -
, -
. PlayingCard (
PlayingCard).
,
while:
491
IsCardAlreadyDealt. , ,
,
null. , ,
Dictionary- cardPack
.
, List<T>-, -
Exists. Find ,
.
, true, -
, false, .
List<T> PlayingCard-,
Exists , true,
PlayingCard ,
, IsCardAlreadyDealt. ,
:
private bool IsCardAlreadyDealt(Suit suit, Value value)
{
List<PlayingCard> cardsInSuit = this.cardPack[suit];
return (!cardsInSuit.Exists(c => c.CardSuit == suit && c.CardValue == value));
}
Hand.cs.
using:
using System.Collections.Generic;
Hand -
cards . ,
492 18
, cards, List<PlayingCard>-
:
class Hand
{
public const int HandSize = 13;
private List<PlayingCard> cards = new List<PlayingCard>(HandSize);
...
}
AddCardToHand.
: , ,
, cards ,
playingCardCount. ,
Add List<PlayingCard>-.
-
, ,
Count. ,
playingCardCount
if, ,
Count, .
,
:
public void AddCardToHand(PlayingCard cardDealt)
{
if (this.cards.Count >= HandSize)
{
throw new ArgumentException("Too many cards");
}
this.cards.Add(cardDealt);
}
,
.
Card Game Deal.
Deal .
.
,
, . Deal,
.
.18.1.
493
. 18.1
,
. , -
,
. - -
.
,
Visual Studio 2015 19 .
Visual Studio 2015,
. -
, .
494 18
, :
List<PlayingCard> cards = new List<PlayingCard>();
- , - - -
( ) -
Add Insert. Queue<T>-
Enqueue, Stack<T>- Push,
:
HashSet<string> employees = new HashSet<string>();
employees.Add(John);
...
LinkedList<int> data = new LinkedList<int>();
data.AddFirst(101);
...
Stack<int> numbers = new Stack<int>();
numbers.Push(99);
, - -
Remove. Queue<T>-
Dequeue, Stack<T>-
Pop, :
HashSet<string> employees = new HashSet<string>();
employees.Remove(John);
...
LinkedList<int> data = new LinkedList<int>();
data.Remove(101);
...
Stack<int> numbers = new Stack<int>();
...
int item = numbers.Pop();
- Count, :
List<PlayingCard> cards = new List<PlayingCard>();
...
int noOfCards = cards.Count;
- -
, .
Find, :
Dictionary<string, int> ages =
new Dictionary<string, int>();
ages.Add(John, 47);
int johnsAge = ages[John];
...
List<Person> personnel = new List<Person>();
Person match = personnel.Find(p => p.ID == 3);
495
: Stack<T>, Queue<T> -
, -
, -
Contains
- for foreach, :
LinkedList<int> numbers = new LinkedList<int>();
...
for (LinkedListNode<int> node = numbers.First;
node != null; node = node.Next)
{
int number = node.Value;
Console.WriteLine(number);
}
...
foreach (int number in numbers)
{
Console.WriteLine(number);
}
19
, :
-
;
-
;
-
.
10 18
, -
. 10
foreach,
. foreach -
, ,
.
, ,
.
10 foreach -
. :
int[] pins = { 9, 3, 7, 2 };
foreach (int pin in pins)
{
Console.WriteLine(pin);
}
497
foreach ,
, -
:
.
? -
, , System.
Collections.IEnumerable.
, C# -
System.Array. , -
IEnumerable.
IEnumerable GetEnumerator:
IEnumerator GetEnumerator();
-,
System.Collections.IEnumerator. - -
() . IEnumerator
:
object Current { get; }
bool MoveNext();
void Reset();
. -
. -
()
MoveNext, true,
, false, . ,
, Current,
Reset. GetEnumerator -
MoveNext,
Current,
. foreach. ,
, -
IEnumerable,
IEnumerator GetEnumerator
.
IEnumerable IEnumerator
, . , -
.
498 19
, , Current
IEnumerator ,
, , .
, , , Microsoft
.NET Framework - IEnumerator<T>,
Current, T.
IEnumerable<T>, GetEnumerator,
Enumerator<T>.
System.Collections.Generic,
.NET Framework 2.0 ,
-,
, .
, -
- IEnumerator<T>
, 17 .
17 ,
. - -
, ,
, .
, . , -
,
MoveNext -
. , ,
, -
.
, ( -
), . ,
, !
TreeEnumerator
Microsoft Visual Studio 2015 BinaryTree, -
\Microsoft Press\VCSBS\Chapter 19\BinaryTree .
BinaryTree, -
17. ,
BinaryTree.
BinaryTree.
,
499
BinaryTree. ,
TreeEnumerator.cs, .
TreeEnumerator, Tree<TItem>-.
,
IEnumerator<T>-. ,
Tree<TItem>-,
, -
IComparable<TItem>- ( BinaryTree ,
,
).
, TreeEnumerator.cs,
TreeEnumerator, . -
:
class TreeEnumerator<TItem> : IEnumerator<TItem> where TItem : IComparable<TItem>
{
}
TreeEnumerator<TItem> ,
:
class TreeEnumerator<TItem> : IEnumerator<TItem> where TItem : IComparable<TItem>
{
private Tree<TItem> currentData = null;
private TItem currentItem = default(TItem);
private Queue<TItem> enumData = null;
}
currentData ,
, currentItem -
, Current. enumData
, , MoveNext
. default
,
.
, TreeEnumerator<TItem>
Tree<TItem>- data. -
, currentData data:
class TreeEnumerator<TItem> : IEnumerator<TItem> where TItem : IComparable<TItem>
{
...
public TreeEnumerator(Tree<TItem> data)
{
this.currentData = data;
}
}
500 19
TreeEnumerator<TItem> -
populate:
enumQueue.Enqueue(tree.NodeData);
if (tree.RightTree != null)
{
populate(enumQueue, tree.RightTree);
}
}
}
,
. , ,
WalkTree Tree<TItem>, -
17. ,
NodeData .
TreeEnumerator<TItem>. -
IEnumerator<TItem>. -
( )
. -
IEnumerator<TItem> IEnumerator,
. Dispose
IDisposable.
IEnumerator<TItem>
IEnumerator IDisposable, - .
, IEnumerator<TItem>, -
- Current. MoveNext Reset -
IEnumerator. IDisposable -
14 .
.
, NotImplementedException.
.
MoveNext , :
501
bool IEnumerator.MoveNext()
{
if (this.enumData == null)
{
this.enumData = new Queue<TItem>();
populate(this.enumData, this.currentData);
}
if (this.enumData.Count > 0)
{
this.currentItem = this.enumData.Dequeue();
return true;
}
return false;
}
MoveNext .
, -
, , .
( MoveNext , , -
Current, ,
.)
populate
, .
MoveNext -
, ,
, , , . ,
MoveNext ,
Current. MoveNext (
currentItem , -
) Current,
true false .
get - Current -
, :
TItem IEnumerator<TItem>.Current
{
get
{
if (this.enumData == null)
{
throw new InvalidOperationException("Use MoveNext before calling
Current");
}
return this.currentItem;
}
}
502 19
,
, , , , -
currentItem, default.
currentItem TItem.
, ,
TItem,
. .
null. ,
TItem, , . (
null,
.) ,
0, , ,
, .
TItem , ,
. default. , -
,
. TItem , default(TItem) -
null, TItem , default(TItem) 0,
TItem , default(TItem) false.
TItem , -
. ( null,
0, false.)
Current.
System.Collections.IEnumerator.Current -
, NotImplementedException.
, MoveNext, Current -
enumData. ( MoveNext
null.) ,
InvalidOperationException , , -
.NET Framework ,
. -
MoveNext,
currentItem, Current
.
IDisposable.Dispose . throw new
NotImplementedException();,
. - ,
, .
. Dispose
14.
503
void IDisposable.Dispose()
{
// throw new NotImplementedException();
}
,
.
IEnumerable
-
, IEnumerable<T>.
TreeEnumerator<TItem> GetEnumerator.
IEnumerable<TItem>
Tree<TItem>
Tree.cs, -
Tree<TItem>. Tree<TItem>
, ,
IEnumerable<TItem>:
, -
.
IEnumerable<TItem>.
. IEnumerable<TItem>.
GetEnumerator IEnumerable.GetEnumerator, .
IEnumerable
, - IEnumerable<TItem>
IEnumerable.
- IEnumerable<TItem>.GetEnumerator, -
. ,
, GetEnumerator(),
throw:
IEnumerator<TItem> IEnumerable<TItem>.GetEnumerator()
{
return new TreeEnumerator<TItem>(this);
}
504 19
GetEnumerator - -
.
TreeEnumerator<TItem>-, , .
,
.
Tree<TItem>, -
foreach.
BinaryTree,
, .
, .
EnumeratorTest, \Microsoft
Press\VCSBS\Chapter 19\BinaryTree ,
OK.
, Visual C#
. -
Visual Basic C++.
Enumera
torTest, .
.
EnumeratorTest
. BinaryTree,
OK. EnumeratorTest
BinaryTree.
Program
using:
using BinaryTree;
Main ,
.
:
static void Main(string[] args)
{
Tree<int> tree1 = new Tree<int>(10);
tree1.Insert(5);
tree1.Insert(11);
tree1.Insert(5);
505
tree1.Insert(-12);
tree1.Insert(15);
tree1.Insert(0);
tree1.Insert(14);
tree1.Insert(-8);
tree1.Insert(10);
}
foreach,
:
static void Main(string[] args)
{
...
foreach (int item in tree1)
{
Console.WriteLine(item);
}
}
.
(.19.1):
12, 8, 0, 5, 5, 10, 10, 11, 14, 15
. 19.1
, -
.
, C# ,
.
506 19
, -
.
, , -
. ,
, C#
. -
,
.
BasicCollection<T>. FillList
List<T>-. -
, BasicCollection<T>
IEnumerable<T>. GetEnumerator :
using System;
using System.Collections.Generic;
using System.Collections;
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
foreach (var datum in data)
{
yield return datum;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
//
throw new NotImplementedException();
}
}
GetEnumerator
. , :
507
IEnumerator<T>.
, .
yield.
, .
, , yield -
, .
, GetEnumerator
, , ,
. ,
GetEnumerator .
.
, .
GetEnumerator .
IEnumerator<T>,
Current MoveNext. -
, GetEnumerator.
, , ( -
, ),
,
. , , ,
,
:
BasicCollection<string> bc = new BasicCollection<string>();
bc.FillList("Twas", "brillig", "and", "the", "slithy", "toves");
foreach (string word in bc)
{
Console.WriteLine(word);
}
bc :
Twas, brillig, and, the, slithy, toves
-
, ,
IEnumerable, -
. , Reverse
BasicCollection<T> , , :
get
{
for (int i = data.Count - 1; i >= 0; i--)
{
yield return data[i];
}
}
}
}
:
BasicCollection<string> bc = new BasicCollection<string>();
bc.FillList("Twas", "brillig", "and", "the", "slithy", "toves");
foreach (string word in bc.Reverse)
{
Console.WriteLine(word);
}
bc :
toves, slithy, the, and, brillig, Twas
Tree<TItem>
Tree<TItem>
. ,
, ,
MoveNext,
,
, ,
, WalkTree, 17.
Tree<TItem>
Visual Studio 2015 BinaryTree,
\Microsoft Press\VCSBS\Chapter 19\IteratorBinaryTree .
BinaryTree, 17.
Tree.cs. Tree<TItem>
, , ,
IEnumerable<TItem>:
public class Tree<TItem> : IEnumerable<TItem> where TItem : IComparable<TItem>
{
...
}
509
-
IEnumerable<TItem>.
,
IEnumerable<TItem>.GetEnumerator IEnumerable.GetEnumerator.
- IEnumerable<TItem>.GetEnumerator. -
GetEnumerator , :
IEnumerator<TItem> IEnumerable<TItem>.GetEnumerator()
{
if (this.LeftTree != null)
{
foreach (TItem item in this.LeftTree)
{
yield return item;
}
}
if (this.RightTree != null)
{
foreach (TItem item in this.RightTree)
{
yield return item;
}
}
}
, , ,
, 17
. LeftTree ,
foreach
GetEnumerator, . -
, .
NodeData ,
. -
, ,
NodeData . -
,
.
BinaryTree,
. -
\Microsoft Press\
VCSBS\Chapter 19\BinaryTree\EnumeratorTest, EnumeratorTest,
510 19
. ,
, .
EnumeratorTest, -
. ,
EnumeratorTest, BinaryTree,
.
.
EnumeratorTest
. BinaryTree,
OK.
, EnumeratorTest -
BinaryTree. ,
, ,
.
Program.cs EnumeratorTest.
Main. ,
Tree<int>-, -
, foreach,
. ,
. -
. , :
, ,
,
IEnumerable<T> IEnumerator<T>. ,
.
,
Visual Studio 2015 20 -
.
Visual Studio 2015, -
.
, .
511
IEnumerable -
, GetEnumerator, IEnumerator,
- :
foreach public class Tree<TItem> : IEnumerable<TItem>
{
...
IEnumerator<TItem> GetEnumerator()
{
...
}
}
, -
IEnumerator,
Current MoveNext (, , -
Reset), :
public class TreeEnumerator<TItem> :
IEnumerator<TItem>
{
...
TItem Current
{
get
{
...
}
}
bool MoveNext()
{
...
}
}
, -
- (
yield) , :
IEnumerator<TItem> GetEnumerator()
{
for (...)
{
yield return ...
}
}
20
, :
;
;
;
- , -
;
;
;
.
.
-
.
. ,
,
,
.
, ,
,
.
, -
.
513
C# . ,
, -
.
,
, . -
, ,
.
Windows (UWP),
.
, .
.
.
, ,
(, ,
).
, :
, , - ,
, .
, ,
, .
.
. , -
. .
, -
, .
, ,
(,, , -
). ,
. ,
performCalculation , Processor
( ,
Processor):
Processor p = new Processor();
p.performCalculation();
514 20
, .
, int- int-.
performCalculationDelegate,
performCalculation,
Processor. ,
, ,
( ):
Processor p = new Processor();
delegate ... performCalculationDelegate ...;
performCalculationDelegate = p.performCalculation;
, , ,
,
- ( -
). .
performCalculation, -
Processor-,
:
performCalculationDelegate();
, , , -
, performCalculationDelegate.
(common language runtime (CLR)) , ,
, , . -
, , ,
, ,
. ,
( -
), , .
, C++, -
. ,
.
, ,
, .
.NETFramework
Microsoft .NET Framework
, 18
Find Exists List<T>. ,
List<T>,
515
, . -
List<T>
, ,
-
. ,
.
Find :
struct Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
...
List<Person> personnel = new List<Person>()
{
new Person() { ID = 1, Name = "John", Age = 47 },
new Person() { ID = 2, Name = "Sid", Age = 28 },
new Person() { ID = 3, Name = "Fred", Age = 34 },
new Person() { ID = 4, Name = "Paul", Age = 22 },
};
...
// , ID 3
Person match = personnel.Find(p => p.ID == 3);
,
List<T>, Average, Max, Min, Count Sum.
Func. ,
( ).
Average
personnel ( Func<T> , Age
), Max -
ID, Count ,
Age 30 39 :
double averageAge = personnel.Average(p => p.Age);
Console.WriteLine($"Average age is {averageAge}");
...
int id = personnel.Max(p => p.ID);
Console.WriteLine($"Person with highest ID is {id}");
...
int thirties = personnel.Count(p => p.Age >= 30 && p.Age <= 39);
Console.WriteLine($"Number of personnel in their thirties is {thirties}");
:
Average age is 32.75
Person with highest ID is 4
Number of personnel in their thirties is 1
516 20
, -
.NET Framework. -
. ,
, ,
.
, Count ,
Func<Person, int>.
, -
List<T>,
, .NET Framework
. System
Func, Func<TResult> , -
, - , Func<T1, T2, T3, T4,
, T16, TResult> , 16 .
, ,
Func. -
Func 21 ,
, .
Func System
Action. Action -
, , ( void).
Action Action<T>
( , ) Action<T1, T2,
T3, T4, , T16>.
,
. ,
517
,
: ,
, .. -
. ,
,
.
, , .
, ,
,
!
, -
,
( ):
StopFolding(); //
FinishWelding(); //
PaintOff(); //
:
class Controller
{
// ,
private FoldingMachine folder;
private WeldingMachine welder;
private PaintingMachine painter;
...
public void ShutDown()
{
folder.StopFolding();
welder.FinishWelding();
painter.PaintOff();
}
...
}
,
.
, , Controller
.
518 20
, : -
. (
, , .)
:
void methodName();
. -
, ,
. :
delegate void stopMachineryDelegate();
:
delegate;
( void),
(stopMachineryDelegate) ( ).
, -
+=. :
class Controller
{
delegate void stopMachineryDelegate(); //
private stopMachineryDelegate stopMachinery; //
...
public Controller()
{
this.stopMachinery += folder.StopFolding;
}
...
}
. , -
, .
, + -
. ( 22
.) , -
.
+= -
. .
519
-
new:
this.stopMachinery = new stopMachineryDelegate(folder.StopFolding);
, :
public void ShutDown()
{
this.stopMachinery();
...
}
, ,
. , , ,
.
, -
,
NullReferenceException.
,
.
, +=:
public Controller()
{
this.stopMachinery += folder.StopFolding;
this.stopMachinery += welder.FinishWelding;
this.stopMachinery += painter.PaintOff;
}
this.stopMachinery -= folder.StopFolding;
Controller. Controller
, stopMachineryDelegate
,
520 20
Controller .
.
stopMachinery :
stopMachinery ,
, :
private stopMachineryDelegate stopMachinery;
...
public stopMachineryDelegate StopMachinery
{
get
{
return this.stopMachinery;
}
set
{
this.stopMachinery = value;
}
}
, Add
Remove. Add
, Remove (
, -
):
public void Add(stopMachineryDelegate stopMethod)
{
this.stopMachinery += stopMethod;
}
- , ,
Add Remove. -
,
.
, ,
, Controller.
Controller ,
(
Add Remove):
521
, -
Wide World Importers,
. ,
,
, Wide World Importers,
. , -
,
. ,
Checkout ( ).
.
.
.
(, -
), .
,
.
-
, , , .
, ,
, -
. ,
,
. ,
, .
,
.
522 20
. 20.1
, Add
(), .
( Age
Restricted Yes). , -
Order Details ( ).
,
. ( -
.)
Order Details Checkout ( ). -
, , .
(ID), ID
. ,
, Visual Studio 2015, .
523
Delegates,
Package.appxmanifest. . -
(Packaging).
(Package Name). -
(globally unique identifier (GUID)).
, %USERPROFILE%\AppData\Local\Packages\
yyy\LocalState, yyy , GUID,
. -
Wide World Importers. ,
audit-nnnnnn.xml ( nnnnnn
), dispatch-nnnnnn.txt.
,
, .
audit-nnnnnn.xml ,
.
,
.
. 20.2
524 20
, Visual Studio.
dispatch-nnnnnn.txt.
ID .
(.20.3).
. 20.3
DataTypes. ,
. Product , -
, ProductsDataSource.
(
. -
-.) Order OrderItem
525
, (order)
(order items).
MainPage.xaml.cs,
Delegates, MainPage.
:
...
private Auditor auditor = null;
private Shipper shipper = null;
public MainPage()
{
...
this.auditor = new Auditor();
this.shipper = new Shipper();
}
, .
, AuditOrder
auditor, ShipOrder shipper.
-.
( if)
:
Order Details.
requestPayment true, ,
. -
.
526 20
, -
, Auditor Shipper ,
. , -
. , , -
, - , ,
,
.
, -
-, .
- Auditor Shipper,
,
.
CheckoutController. -
-
, ,
. CheckoutController
.
CheckoutController
Delegates,
, .
Windows, -
.
( Windows). CheckoutService,
OK.
CheckoutService, -
Class1.cs .
CheckoutController.cs, . ,
Visual Studio Class1 CheckoutController.
CheckoutService ,
.
CheckoutService .
DataTypes, OK. CheckoutController
Order, DataTypes.
CheckoutController.cs
using:
using DataTypes;
CheckoutController
CheckoutDelegate, :
527
,
Order .
AuditOrder ShipOrder Auditor Shipper.
CheckoutProcessing:
MainPage.xaml.cs Delegates
requestPayment ( ). MainPage.
CheckoutController.cs requestPayment
CheckoutController, ,
:
public class CheckoutController
{
public delegate void CheckoutDelegate(Order order);
public CheckoutDelegate CheckoutProcessing = null;
// ,
// true, ,
return true;
}
}
CheckoutController StartCheckoutProcessing, -
:
public class CheckoutController
{
public delegate void CheckoutDelegate(Order order);
public CheckoutDelegate CheckoutProcessing = null;
{
//
if (this.requestPayment())
{
if (this.CheckoutProcessing != null)
{
this.CheckoutProcessing(order);
}
}
}
}
,
CheckoutButtonClicked MainPage. -
, CheckoutProcessing:
null (
), . ,
.
Delegates
, .
Delegates .
CheckoutService, OK.
MainPage.xaml.cs Delegates
using:
using CheckoutService;
MainPage -
checkoutController, CheckoutController, -
null:
public ... class MainPage : ...
{
...
private Auditor auditor = null;
private Shipper shipper = null;
private CheckoutController checkoutController = null;
...
}
MainPage. , -
Auditor Shipper, CheckoutController,
:
public MainPage()
{
...
this.auditor = new Auditor();
this.shipper = new Shipper();
this.checkoutController = new CheckoutController();
}
529
, :
public MainPage()
{
...
this.checkoutController = new CheckoutController();
this.checkoutController.CheckoutProcessing += this.auditor.AuditOrder;
this.checkoutController.CheckoutProcessing += this.shipper.ShipOrder;
}
CheckoutProcessing CheckoutController
AuditOrder ShipOrder Auditor Shipper.
CheckoutButtonClicked. try ,
( if), ,
:
private void CheckoutButtonClicked(object sender, RoutedEventArgs e)
{
try
{
//
this.checkoutController.StartCheckoutProcessing(this.order);
//
...
}
...
}
, , ,
.
CheckoutController, , -
MainPage.
.
. Wide World Importers,
( -
), Checkout.
Order Placed,
, Close OK.
%USERPROFILE%\AppData\Local\Packages\
yyy\LocalState, yyy ,
GUID. ,
530 20
-
-
. , -
StopFolding folder
stopMachinery :
this.stopMachinery += folder.StopFolding;
, , -
. , StopFolding :
FinishWelding PaintOff,
. ?
-
FinishFolding, , -
:
void FinishFolding()
{
folder.StopFolding(0); //
}
FinishFolding stopMachinery
StopFolding, , :
this.stopMachinery += folder.FinishFolding;
stopMachinery FinishFolding,
StopFolding, 0.
531
FinishFolding
, ( ) ,
. -
, (Erich Gamma),
(Richard Helm), (Ralph Johnson) (John Vlissides)
- .
(Addison-Wesley Professional, 1994).
-
, .
, , , -
StopFolding
. C# -.
18,
.
-:
this.stopMachinery += (() => folder.StopFolding(0));
stopMachinery , -
-, StopFolding -
.
, ,
. .
,
.
- .
,
stopMachinery
.
.NET Framework ,
, .
.NET Framework. ,
UWP-, Windows
, , ,
- .
.
532 20
, -
. ,
, - .
, -
.
, ,
, .
, .
.
.
, . -
, ,
event.
:
, , StopMachineryDelegate
. TemperatureMonitor,
( ,
Controller):
class TemperatureMonitor
{
public delegate void StopMachineryDelegate();
...
}
MachineOverheating, stopMachineryDelegate,
:
class TemperatureMonitor
{
public delegate void StopMachineryDelegate();
public event StopMachineryDelegate MachineOverheating;
...
}
TemperatureMonitor ( ) -
MachineOverheating. ( -
, .)
533
( ), ,
. .
, +=. -
. -
, ,
, ,
MachineOverheating :
class TemperatureMonitor
{
public delegate void StopMachineryDelegate();
public event StopMachineryDelegate MachineOverheating;
...
}
...
TemperatureMonitor tempMonitor = new TemperatureMonitor();
...
tempMonitor.MachineOverheating += (() => { folder.StopFolding(0); });
tempMonitor.MachineOverheating += welder.FinishWelding;
tempMonitor.MachineOverheating += painter.PaintOff;
, ,
. ,
-. tempMonitor.
MachineOverheating,
.
, +=,
,
=. =
, .
.
, . -
. ,
534 20
TemperatureMonitor
Notify, MachineOverheating:
class TemperatureMonitor
{
public delegate void StopMachineryDelegate();
public event StopMachineryDelegate MachineOverheating;
...
private void Notify()
{
if (this.MachineOverheating != null)
{
this.MachineOverheating();
}
}
...
}
. null ,
null , -
+= - .
, null,
NullReferenceException. , ,
- ,
.
.
-
. , MachineOverheating,
, ( TemperatureMonitor).
,
.
, .NET Framework
, -
. , Button,
ButtonBase, Click,
RoutedEventHandler. RoutedEventHandler -
: , ,
RoutedEventArgs, :
Button :
public class ButtonBase: ...
{
public event RoutedEventHandler Click;
...
}
, Button -
Click.
. UWP-, -
, okay, Click
okay okayClick:
partial class MainPage :
global::Windows.UI.Xaml.Controls.Page,
global::Windows.UI.Xaml.Markup.IComponentConnector,
global::Windows.UI.Xaml.Markup.IComponentConnector2
{
...
public void Connect(int connectionId, object target)
{
switch(connectionId)
{
case 1:
{
this.okay = (global::Windows.UI.Xaml.Controls.Button)(target);
...
((global::Windows.UI.Xaml.Controls.Button)this.okay).Click +=
this.okayClick;
...
}
break;
default:
break;
}
this._contentLoaded = true;
}
...
}
. Visual Studio
2015 XAML
Click okay okayClick Visual Studio 2015
.
536 20
okayClick, ,
MainPage.xaml.cs:
public sealed partial class MainPage : Page
{
...
private void okayClick(object sender, RoutedEventArgs e)
{
// Click
}
}
, -
, .
,
void .
() sender,
EventArgs ( , EventArgs).
sender
.
sender . ,
Click .
( .) -
sender,
, .
Wide World Importers
, -
. CheckoutController
, CheckoutController -
. , ,
-
.
, -
,
CheckoutController , , -
,
, .
537
! 24
,
,
-
. UWP-,
, ,
. CheckoutButtonClicked Wide World Importers
, , , -
, :
private void CheckoutButtonClicked(object sender, RoutedEventArgs e)
{
try
{
// ,
this.checkoutController.StartCheckoutProcessing(this.order);
//
MessageDialog dlg = new MessageDialog(...);
dlg.ShowAsync();
...
}
...
}
, ,
, , ,
.
-
. , Auditor, Shipper, ,
.
. , -
, ,
.
Auditor Shipper,
, -
. -
.
CheckoutController
Visual Studio 2015 Delegates. -
Auditor.cs, AuditService. Auditor
538 20
AuditingCompleteDelegate.
, message
void. :
class Auditor
{
public delegate void AuditingCompleteDelegate(string message);
...
}
Auditor AuditingCompleteDelegate
AuditProcessingComplete. ,
, AuditingCompleteDelegate:
class Auditor
{
public delegate void AuditingCompleteDelegate(string message);
public event AuditingCompleteDelegate AuditProcessingComplete;
...
}
AuditOrder. , -
CheckoutController-.
doAuditing .
:
public void AuditOrder(Order order)
{
this.doAuditing(order);
}
doAuditing. try-
catch. XML-
XML API-
.NET Framework. (
.)
catch finally, AuditPro
cessingComplete :
Shipper.cs, DeliveryService.
Shipper ShippingCompleteDelegate.
, message
void.
:
class Shipper
{
public delegate void ShippingCompleteDelegate(string message);
...
}
Shipper
ShipProcessingComplete, ShippingCompleteDelegate:
class Shipper
{
public delegate void ShippingCompleteDelegate(string message);
public event ShippingCompleteDelegate ShipProcessingComplete;
...
}
doShipping, .
catch
finally, ShipProcessingComplete:
finally
{
if (this.ShipProcessingComplete != null)
{
this.ShipProcessingComplete(
$"Dispatch note generated for Order {order.OrderID}");
}
}
}
MainPage.xaml, -
Delegates. XAML
RowDefinition. XAML
:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid Margin="12,0,12,0" Loaded="MainPageLoaded">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
...
Height RowDefinition, -
, 2*:
<Grid.RowDefinitions>
...
<RowDefinition Height="10*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
,
, Auditor Shipper ,
.
Grid 25
Windows.
XAML- . -
</Grid>
ScrollViewer TextBlock:
...
</Grid>
<ScrollViewer Grid.Row="4" VerticalScrollBarVisibility="Visible">
541
TextBlock messageBar.
Auditor Shipper.
MainPage.xaml.cs. Checkout
ButtonClicked , .
try :
private void CheckoutButtonClicked(object sender, RoutedEventArgs e)
{
try
{
// ,
this.checkoutController.StartCheckoutProcessing(this.order);
// ,
//
MainPage displayMessage.
message
void. ,
message Text messageBar
TextBlock, (
):
private void displayMessage(string message)
{
this.messageBar.Text += message + "\n";
}
.
542 20
MainPage ,
:
public MainPage()
{
...
this.auditor = new Auditor();
this.shipper = new Shipper();
this.checkoutController = new CheckoutController();
this.checkoutController.CheckoutProcessing += this.auditor.AuditOrder;
this.checkoutController.CheckoutProcessing += this.shipper.ShipOrder;
this.auditor.AuditProcessingComplete += this.displayMessage;
this.shipper.ShipProcessingComplete += this.displayMessage;
}
, -
Auditor Shipper .
displayMessage. ,
.
,
.
Wide World Importers, ,
,
Checkout.
, TextBlock
Audit record written, -
Dispatch note generated (.20.4).
. 20.4
,
Checkout ( ,
).
, Visual Studio 2015 .
543
-
. , -,
. ,
.
,
Visual Studio 2015 21.
Visual Studio 2015, -
.
, .
delegate,
,
, :
delegate void myDelegate();
, -
, - :
- new, ( ),
.
, -
, :
delegate void myDelegate();
private void myMethod() { ... }
...
myDelegate del = new myDelegate(this.myMethod);
, ,
:
myDelegate del;
...
del();
event,
( ),
, :
class MyClass
{
public delegate void MyDelegate();
544 20
...
public event myDelegate MyEvent;
}
- ( , )
, -
+=, :
class MyEventHandlingClass
{
private MyClass myClass = new MyClass();
...
public void Start()
{
myClass.MyEvent += new myClass.MyDelegate
(this.eventHandlingMethod);
}
private void eventHandlingMethod()
{
...
}
}
,
:
public void Start()
{
myClass.MyEvent += this.eventHandlingMethod;
}
( , )
, -
=, :
class MyEventHandlingClass
{
private MyClass myClass = new MyClass();
...
public void Stop()
{
myClass.MyEvent -= new myClass.MyDelegate
(this.eventHandlingMethod);
}
...
}
:
public void Stop()
{
myClass.MyEvent -= this.eventHandlingMethod;
}
545
- ,
.
, ,
. -
null-, :
class MyClass
{
public event myDelegate MyEvent;
...
private void RaiseEvent()
{
if (this.MyEvent != null)
{
this.MyEvent();
}
}
...
}
21 ,
,
, :
C# (Language-
Integrated Query (LINQ))
;
LINQ ;
, LINQ -
LINQ- -
.
C# .
,
: C#
. ,
.
, , -
? ,
Customer, , ,
, ,
? -
,
, C#
-
.
C#, .
LINQ? 547
LINQ?
, ,
, . ,
. , -
.
,
, . Microsoft .NET
Framework
,
, ,
, . Language-
Integrated Query (LINQ).
LINQ , -
, Microsoft
SQL Server, , ,
.
SQL Server,
(Structured Query Language (SQL)). SQL
, ,
,
.
. , , SQL-,
,
. ,
, (, ),
SQL-, -
.
LINQ , SQL
. -
,
, . :
LINQ- SQL,
. LINQ
, , , -
XML-.
LINQ .
548 21
LINQ C#
, C#,
LINQ, ,
(.21.1 21.2).
21.1
21.2
LINQ- , ,
IEnumerable IEnumerable<T> -
, 19 . -
, (, HashSet<T>, Queue<T>
,
), , . -
, ,
customers addresses,
.
-
.
var customers = new[] {
new { CustomerID = 1, FirstName = "Kim", LastName = "Abercrombie",
CompanyName = "Alpine Ski House" },
new { CustomerID = 2, FirstName = "Jeff", LastName = "Hay",
CompanyName = "Coho Winery" },
new { CustomerID = 3, FirstName = "Charlie", LastName = "Herb",
CompanyName = "Alpine Ski House" },
new { CustomerID = 4, FirstName = "Chris", LastName = "Preston",
CompanyName = "Trey Research" },
new { CustomerID = 5, FirstName = "Dave", LastName = "Barnett",
CompanyName = "Wingtip Toys" },
new { CustomerID = 6, FirstName = "Ann", LastName = "Beebe",
CompanyName = "Coho Winery" },
new { CustomerID = 7, FirstName = "John", LastName = "Kane",
CompanyName = "Wingtip Toys" },
new { CustomerID = 8, FirstName = "David", LastName = "Simpson",
CompanyName = "Trey Research" },
new { CustomerID = 9, FirstName = "Greg", LastName = "Chapman",
CompanyName = "Wingtip Toys" },
new { CustomerID = 10, FirstName = "Tim", LastName = "Litton",
CompanyName = "Wide World Importers" }
};
, , ,
,
LINQ. , -
, ,
, , .
,
, , C#, -
.
, ,
, customers.
:
IEnumerable<string> customerFirstNames =
customers.Select(cust => cust.FirstName);
,
,
Select customers.
Select , -
FirstName .
? Select
, customers
. -
, , ,
-
. :
cust , . cust
customers.
, Select -
customers. cust -
C#.
Select , -
, ,
LINQ C# 551
Select .
LINQ LINQ .
Select Array. -
Enumerable, System.
Linq
, - IEnumerable<T>.
Select customers -
IEnumerable<string>- customerFirstNames. (
IEnumerable<string>, Select
, .) foreach -
,
:
Kim
Jeff
Charlie
Chris
Dave
Ann
John
David
Greg
Tim
.
? . -
Enumerable.Select System.Linq
, Microsoft Visual Studio 2015,
:
public static IEnumerable<TResult> Select<TSource, TResult> (
this IEnumerable<TSource> source,
Func<TSource, TResult> selector
)
, , Select -,
TSource TResult,
source selector. TSource -
, (
customer), TResult
( ). ,
Select , source
, (
customer, IEnumerable).
selector -,
552 21
. ( , Func -
.NET Framework, -
, .) ,
selector, TSource ( customer)
TResult ( string). ,
Select, TResult (
string).
, 12 .
, Select -
, . ,
,
, .
Select :
IEnumerable<string> customerNames =
customers.Select(cust => $"{cust.FirstName} {cust.LastName}");
, , -
Select :
class FullName
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
...
IEnumerable<FullName> customerNames =
customers.Select(cust => new FullName
{
FirstName = cust.FirstName,
LastName = cust.LastName
} );
, ,
FullName, , ,
, :
var customerNames =
customers.Select(cust => new { FirstName = cust.FirstName,
LastName = cust.LastName } );
var. -
,
.
LINQ C# 553
Select, ,
.
, -
. , , ,
addresses, -
. Where:
IEnumerable<string> usCompanies =
addresses.Where(addr => String.Equals(addr.Country, "United States"))
.Select(usComp => usComp.CompanyName);
Where Select. -
, ,
. -. -
addr addresses, --
, Country
United States. Where
, . -
Select,
CompanyName
. ( usComp
, Where.) ,
IEnumerable<string>.
:
Where, Select.
foreach, ,
:
Coho Winery
Trey Research
, SQL, ,
.
, ,
554 21
,
,
. LINQ .
, -
OrderBy. , Select Where, OrderBy
.
, . ,
addresses -
:
IEnumerable<string> companyNames =
addresses.OrderBy(addr => addr.CompanyName).Select(comp => comp.CompanyName);
, ,
:
Alpine Ski House
Coho Winery
Trey Research
Wide World Importers
Wingtip Toys
,
OrderByDescending.
, OrderBy OrderByDescending -
ThenBy ThenByDescending.
, GroupBy.
, addresses :
var companiesGroupedByCountry =
addresses.GroupBy(addrs => addrs.Country);
. GroupBy -
, , .
GroupBy , .
Select
, . ,
GroupBy, ,
, ,
GroupBy. , GroupBy
, -
.
companiesGroupedByCountry .
,
, . ,
, companiesGroupedByCountry
foreach,
foreach. , foreach
Key
, ,
, Count, Max, Min
. :
Country: Switzerland 1 companies
Alpine Ski House
Country: United States 2 companies
Coho Winery
Trey Research
Country: United Kingdom 2 companies
Wingtip Toys
Wide World Importers
, , Count,
Max Min, ,
Select. , -
addresses, :
int numberOfCompanies = addresses.Select(addr => addr.CompanyName).Count();
Console.WriteLine($"Number of companies: {numberOfCompanies}");
,
, .
:
Number of companies: 5
. , -
, ,
556 21
. , ,
addresses, CompanyName. ,
, -
:
int numberOfCountries = addresses.Select(addr => addr.Country).Count();
Console.WriteLine($"Number of countries: {numberOfCountries}");
:
Number of countries: 5
addresses
, United States, United Kingdom .
Distinct:
int numberOfCountries =
addresses.Select(addr => addr.Country).Distinct().Count();
Console.WriteLine($"Number of countries: {numberOfCountries}");
Console.WriteLine
:
Number of countries: 3
, SQL, LINQ -
.
,
:
var companiesAndCustomers = customers
.Select(c => new { c.FirstName, c.LastName, c.CompanyName })
.Join(addresses, custs => custs.CompanyName, addrs => addrs.CompanyName,
(custs, addrs) => new {custs.FirstName, custs.LastName, addrs.Country });
customers,
, , addresses.
customers addresses .
LINQ C# 557
, ,
Select;
, ,
;
, , -
, Join.
Join , -
FirstName, LastName CompanyName customers,
addresses. ,
CompanyName customers CompanyName
addresses.
, FirstName LastName customers,
Country addresses. ,
companiesAndCustomers, :
, -
. -
,
.
, ,
, , -
addresses, -
. , -
. , -
.
558 21
-
, -
Enumerable,
System.Linq.
C#,
. ,
C# , -
LINQ, ,
SQL.
, , ,
:
IEnumerable<string> customerFirstNames =
customers.Select(cust => cust.FirstName);
, from select:
C# -
Select. from -
, select ,
.
. , SQL, ,
from select.
,
. ( -
,
Select.)
where.
, addresses , -
:
orderby:
var companyNames = from a in addresses
orderby a.CompanyName
select a.CompanyName;
group:
var companiesGroupedByCountry = from a in addresses
group a by a.Country;
, -
select
, :
foreach (var companiesPerCountry in companiesGroupedByCountry)
{
Console.WriteLine(
$"Country: {companiesPerCountry.Key}\t{companiesPerCountry.Count()}
companies");
foreach (var companies in companiesPerCountry)
{
Console.WriteLine($"\t{companies.CompanyName}");
}
}
, Count, -
, ,
:
int numberOfCompanies = (from a in addresses
select a.CompanyName).Count();
, . -
, Distinct:
int numberOfCountries = (from a in addresses
select a.Country).Distinct().Count();
,
.
Count :
int numberOfCompanies = addresses.Count();
join -
. ,
customers addresses CompanyName -
, join.
equals on.
560 21
LINQ
equi-joins ( ). ,
SQL,
, > <, LINQ -
.
var countriesAndCustomers = from a in addresses
join c in customers
on a.CompanyName equals c.CompanyName
select new { c.FirstName, c.LastName, a.Country };
SQL, on LINQ-
. (
from) equals,
, (
join), .
, -
LINQ
.
. , LINQ Intersect
Union,
. , Any
All,
-
.
, Take Skip.
LINQ ,
Visual Studio 2015.
Tree<TItem>
, -
.
, - IEnumerable<T>.
-
. BinaryTree,
Employee, -
LINQ. LINQ
, .
BinaryTree
Program.cs, Program -
Main doWork, .
QueryBinaryTree, . -
Query BinaryTree
Employee.cs .
Employee ,
:
class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
public int Id { get; set; }
}
Employee
ToString. .NET Framework
,
Console.WriteLine:
class Employee
{
...
public override string ToString()
{
return
$"Id: {this.Id}, Name: {this.FirstName} {this.LastName}, Dept: {this.
Department}";
}
}
Employee , -
IComparable<Employee>:
class Employee : IComparable<Employee>
{
}
, BinaryTree ,
.
IComparable<Employee>
, , -
.
CompareTo. ,
BinaryTree ,
.
562 21
CompareTo ,
. CompareTo Employee
Id:
int IComparable<Employee>.CompareTo(Employee other)
{
if (other == null)
{
return 1;
}
IComparable<T> 19.
QueryBinaryTree,
. Microsoft
Press\VCSBS\Chapter 21\BinaryTree ,
BinaryTree, . BinaryTree -
BinaryTree, 19.
QueryBinaryTree, . -
QueryBinaryTree -
. BinaryTree,
OK.
Program.cs QueryBinaryTree
, using
:
using System.Linq;
Program.cs using,
BinaryTree:
using BinaryTree;
LINQ C# 563
doWork
. Select ,
.
static void doWork()
{
...
Console.WriteLine("List of departments");
var depts = empTree.Select(d => d.Department);
.
:
List of departments
Department: IT
Department: Marketing
Department: Sales
Department: IT
Department: Marketing
Department: Sales
564 21
,
.
CompareTo Employee, -
Id .
Id, 1, Id,
2, ..
, Visual Studio 2015.
doWork Program , -
,
:
var depts = empTree.Select(d => d.Department).Distinct();
Distinct .
.
,
:
List of departments
Department: IT
Department: Marketing
Department: Sales
doWork ,
. ,
LINQ C# 565
, GroupBy.
foreach , -
. foreach
:
static void doWork()
{
...
Console.WriteLine("\nAll employees grouped by department");
var employeesByDept = empTree.GroupBy(e => e.Department);
. , -
:
List of departments
Department: IT
Department: Marketing
Department: Sales
BinaryTree
doWork , -
, ,
, from select:
566 21
, IT-
, , :
// var ITEmployees =
// empTree.Where(e => String.Equals(e.Department, "IT"))
// .Select(emp => emp);
var ITEmployees = from e in empTree
where String.Equals(e.Department, "IT")
select e;
, , -
, ,
:
// var employeesByDept = empTree.GroupBy(e => e.Department);
var employeesByDept = from e in empTree
group e by e.Department;
. , -
, :
List of departments
Department: IT
Department: Marketing
Department: Sales
Employees in the IT department
Id: 1, Name: Kim Abercrombie, Dept: IT
Id: 4, Name: Charlie Herb, Dept: IT
All employees grouped by department
Department: IT
Kim Abercrombie
Charlie Herb
Department: Marketing
Jeff Hay
Tim Litton
Department: Sales
Dave Barnett
Chris Preston
LINQ
LINQ -
LINQ,
, ,
LINQ C# 567
LINQ ,
. , -
LINQ- , ,
:
. , (
) , -
:
var usCompanies = from a in addresses
where String.Equals(a.Country, "United States")
select a.CompanyName;
addresses , ,
Where, ,
usCompanies:
foreach (string name in usCompanies)
{
Console.WriteLine(name);
}
addresses -
usCompanies (,
, ), .
.
LINQ- ,
.
. List-
LINQ ToList, .
:
var usCompanies = from a in addresses.ToList()
where String.Equals(a.Country, "United States")
select a.CompanyName;
. -
address ,
usCompanies . LINQ
ToArray,
.
-
LINQ-
.
568 21
LINQ-
Visual Studio 2015 Program.cs
QueryBinaryTree. doWork, -
, empTree:
static void doWork()
{
Tree<Employee> empTree = new Tree<Employee>(
new Employee { Id = 1, FirstName = "Kim", LastName = "Abercrombie",
Department = "IT"});
empTree.Insert(
new Employee { Id = 2, FirstName = "Jeff", LastName = "Hay",
Department = "Marketing"});
empTree.Insert(
new Employee { Id = 4, FirstName = "Charlie", LastName = "Herb",
Department = "IT"});
empTree.Insert(
new Employee { Id = 6, FirstName = "Chris", LastName = "Preston",
Department = "Sales"});
empTree.Insert(
new Employee { Id = 3, FirstName = "Dave", LastName = "Barnett",
Department = "Sales"});
empTree.Insert(
new Employee { Id = 5, FirstName = "Tim", LastName = "Litton",
Department="Marketing"});
//
...
}
,
.
, Ctrl , , K C.
doWork , -
empTree, , :
static void doWork()
{
...
Console.WriteLine("All employees");
var allEmployees = from e in empTree
select e;
allEmployees,
, -
, .
:
static void doWork()
{
...
empTree.Insert(new Employee
{
Id = 7,
FirstName = "David",
LastName = "Simpson",
Department = "IT"
});
Console.WriteLine("\nEmployee added");
Console.WriteLine("All employees");
foreach (var emp in allEmployees)
{
Console.WriteLine(emp);
}
...
}
empTree ,
allEmployees.
. , -
:
All employees
Id: 1, Name: Kim Abercrombie, Dept: IT
Id: 2, Name: Jeff Hay, Dept: Marketing
Id: 3, Name: Dave Barnett, Dept: Sales
Id: 4, Name: Charlie Herb, Dept: IT
Id: 5, Name: Tim Litton, Dept: Marketing
Id: 6, Name: Chris Preston, Dept: Sales
Employee added
All employees
Id: 1, Name: Kim Abercrombie, Dept: IT
Id: 2, Name: Jeff Hay, Dept: Marketing
Id: 3, Name: Dave Barnett, Dept: Sales
Id: 4, Name: Charlie Herb, Dept: IT
Id: 5, Name: Tim Litton, Dept: Marketing
Id: 6, Name: Chris Preston, Dept: Sales
Id: 7, Name: David Simpson, Dept: IT
, -
allEmployees David
570 21
Simpson,
allEmployees.
LINQ
ToList ToArray.
, -
. , select, Employee-,
- allEmployees
List<Employee>.
. , -
:
All employees
Id: 1, Name: Kim Abercrombie, Dept: IT
Id: 2, Name: Jeff Hay, Dept: Marketing
Id: 3, Name: Dave Barnett, Dept: Sales
Id: 4, Name: Charlie Herb, Dept: IT
Id: 5, Name: Tim Litton, Dept: Marketing
Id: 6, Name: Chris Preston, Dept: Sales
Employee added
All employees
Id: 1, Name: Kim Abercrombie, Dept: IT
Id: 2, Name: Jeff Hay, Dept: Marketing
Id: 3, Name: Dave Barnett, Dept: Sales
Id: 4, Name: Charlie Herb, Dept: IT
Id: 5, Name: Tim Litton, Dept: Marketing
Id: 6, Name: Chris Preston, Dept: Sales
,
allEmployees David Simpson.
, , David
Simpson empTree.
LINQ -
IEnumerable<T>, -
. ,
C#.
,
Visual Studio 2015 22 .
Visual Studio 2015, -
.
, .
- Select -,
- , :
- var customerFirstNames = customers.Select(cust =>
cust.FirstName);
from select, -
:
var customerFirstNames =
from cust in customers
select cust.FirstName;
Where -,
- , -
, :
var usCompanies =
addresses.Where(addr =>
String.Equals(addr.Country, United States))
.Select(usComp => usComp.CompanyName);
where, :
var usCompanies =
from a in addresses
where String.Equals(a.Country, United States)
select a.CompanyName;
- OrderBy --
- , , ,
:
572 21
var companyNames =
addresses.OrderBy(addr => addr.CompanyName)
.Select(comp => comp.CompanyName);
orderby, :
var companyNames =
from a in addresses
orderby a.CompanyName
select a.CompanyName;
GroupBy --
- , , ,
:
var companiesGroupedByCountry =
addresses.GroupBy(addrs => addrs.Country);
group by, -
:
var companiesGroupedByCountry =
from a in addresses
group a by a.Country;
- Join, ,
, ,
- , :
var countriesAndCustomers =
customers
.Select(c => new { c.FirstName,
c.LastName,c.CompanyName }).
Join(addresses, custs => custs.CompanyName,
addrs => addrs.CompanyName,
(custs, addrs) => new {custs.FirstName,
custs.LastName, addrs.Country });
join, :
var countriesAndCustomers =
from a in addresses
join c in customers
on a.CompanyName equals c.CompanyName
select new { c.FirstName, c.LastName, a.Country
};
, :
;
;
-
;
;
-
;
-
.
(,
) (-
, + ).
. ,
.
.
, ,
.
.
, ,
574 22
. , ,
+ , .
. , *
+. , a + b * c
a + (b * c).
,
: . ,
= (
), , a = b = c -
a = (b = c).
, , . ,
(++).
, , . , -
(*).
,
, C#
. C#
,
.
.
, -
(, +), ,
(, int).
, a + b * c
a + (b * c) a, b c.
. , * (
) . *
, .
. ,
, **.
.
, -
. , 1 + 2 ,
. ,
.
575
, . ,
(.), -
. ,
.
[ ] -
.
(=) ,
.
, , -
. ,
, ,
operator . -
,
Hour, +
Hour:
struct Hour
{
public Hour(int initialValue)
{
this.value = initialValue;
}
public static Hour operator +(Hour lhs, Hour rhs)
{
return new Hour(lhs.value + rhs.value);
}
...
private int value;
}
.
(public). -
.
( static ).
. ,
virtual, abstract,
override sealed.
(, +, ) -
,
576 22
. (, C++,
, this .)
,
, .
, lhs rhs
( , (left-hand side), ,
(right-hand side), ).
+ Hour -
C# +.
C#
Hour Example(Hour a, Hour b)
{
return a + b;
}
:
Hour Example(Hour a, Hour b)
{
return Hour.operator +(a,b); //
}
, ,
C#. -
( ).
, ,
:
. operator + Hour ,
ab, Hour-.
Hour. ,
operator+ , , ( )
Hour Hour,
. , ,
,
.
, +
Hour. Hour
, Hour int. Hour
int, , , -
Hour- int Hour:
577
Hour a = ...;
int b = ...;
Hour sum = a + new Hour(b);
, , -
Hour int:
Hour a = ...;
int b = ...;
Hour sum = a + b;
a + b, ,
Hour ( a) int ( b). ,
+, Hour, -
int. :
struct Hour
{
public Hour(int initialValue)
{
this.value = initialValue;
}
...
public static Hour operator +(Hour lhs, Hour rhs)
{
return new Hour(lhs.value + rhs.value);
}
public static Hour operator +(Hour lhs, int rhs)
{
return lhs + new Hour(rhs);
}
...
private int value;
}
,
Hour , int, .
, .
, + -
. ,
,
,
,
.
+ , Hour, -
, int,
. , int,
578 22
, Hour,
:
int a = ...;
Hour b = ...;
Hour sum = a + b; //
. a + b,
, b + a.
+:
struct Hour
{
public Hour(int initialValue)
{
this.value = initialValue;
}
...
public static Hour operator +(Hour lhs, int rhs)
{
return lhs + new Hour(rhs);
}
public static Hour operator +(int lhs, Hour rhs)
{
return new Hour(lhs) + rhs;
}
...
private int value;
}
, C++, ,
. -
,
.
,
-
(common language runtime (CLR)).
, ,
, -
. , , +
Hour :
public static Hour operator +(Hour lhs, int rhs)
{
...
}
579
-
, Microsoft Visual Basic,
Add, :
public static Hour Add(Hour lhs, int rhs)
{
...
}
(, +=) -
(, +). ,
a += b;
a = a + b;
a @= b, @ -
, a = a @ b. -
,
-
:
Hour a = ...;
int b = ...;
a += a; // , a = a + a
a += b; // , a = a + b
a += a , -
a Hour, Hour +,
Hour.
a += b, a
Hour, b int. Hour +,
Hour-, int-.
, b += a, -
, b = b + a. ,
,
Hour , int, .
580 22
C#
(++) ().
: ,
. Hour
:
struct Hour
{
...
public static Hour operator ++(Hour arg)
{
arg.value++;
return arg;
}
...
private int value;
}
,
. C# -
,
.
, . ,
Hour now = new Hour(9);
Hour postfix = now++;
Hour now = new Hour(9);
Hour postfix = now;
now = Hour.operator ++(now); // , C#
, ,
, C#
Hour now = new Hour(9);
Hour prefix = ++now;
Hour now = new Hour(9);
now = Hour.operator ++(now); // , C#
Hour prefix = now;
581
,
.
, Hour
, Hour . Hour
, ,
, .
, , , ,
, ,
, Hour
, :
Hour now = new Hour(9);
Hour postfix = now;
now = Hour.operator ++(now); // , C#
Hour , postfix = -
postfix ,
now. now postfix!
Hour , now
postfix now postfix,
.
Hour
:
class Hour
{
public Hour(int initialValue)
{
this.value = initialValue;
}
...
public static Hour operator ++(Hour arg)
{
return new Hour(arg.value + 1);
}
...
private int value;
}
, ++ -
. ,
582 22
. , -
,
-
. -
. ,
.
.
, Hour
!=, Hour-
==. C#
, , ==,
!= .
< >, <= >=.
.
-
. == !=
Hour :
struct Hour
{
public Hour(int initialValue)
{
this.value = initialValue;
}
...
public static bool operator ==(Hour lhs, Hour rhs)
{
return lhs.value == rhs.value;
}
public static bool operator !=(Hour lhs, Hour rhs)
{
return lhs.value != rhs.value;
}
...
private int value;
}
.
-
,
.
583
== !=,
Equals GetHashCode, System.Object ( System.ValueType,
). Equals
, ==. (
.) GetHashCode Microsoft
.NET Framework. (, , -
, , -,
GetHashCode.
.NET Framework, Visual Studio 2015.)
.
GetHashCode , -
.
,
.
: .
(x + yi), x -
, yi . x y
, i 1 ( yi
).
,
, ,
, .
, -
, , -
.
-
, x y -
. ,
. .22.1
, (a + bi) (c + di).
584 22
22.1
Complex
.
Complex , :
class Complex
{
...
public Complex (int real, int imaginary)
{
this.Real = real;
this.Imaginary = imaginary;
}
}
585
int-
Real Imaginary. ToString, , -
:
class Complex
{
...
public override string ToString()
{
return $"({this.Real} + {this.Imaginary}i)";
}
}
,
(x+yi). Complex +,
:
class Complex
{
...
public static Complex operator +(Complex lhs, Complex rhs)
{
return new Complex(lhs.Real + rhs.Real, lhs.Imaginary + rhs.Imaginary);
}
}
. Complex- -
, , .22.1.
Complex-, .
Complex -:
class Complex
{
...
public static Complex operator -(Complex lhs, Complex rhs)
{
return new Complex(lhs.Real - rhs.Real, lhs.Imaginary - rhs.Imaginary);
}
}
, -
+.
* /:
class Complex
{
...
public static Complex operator *(Complex lhs, Complex rhs)
{
586 22
, -
, . ( -
/ ,
.)
Program.cs. doWork
, ,
// TODO::
Console.WriteLine($"first is {first}");
Console.WriteLine($"second is {second}");
Complex-, -
(10 + 4i) (5 + 2i). ,
, .
. , -
, .22.1.
587
. 22.1
Visual Studio 2015 Complex.cs.
Complex == !=, :
class Complex
{
...
public static bool operator ==(Complex lhs, Complex rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(Complex lhs, Complex rhs)
{
return !(lhs.Equals(rhs));
}
}
, Equals, -
,
. true, , false,
.
.
:
'ComplexNumbers.Complex' defines operator == or operator != but does not override
Object.Equals(object o)
'ComplexNumbers.Complex' defines operator == or operator != but does not override
Object.GetHashCode()
!= ==,
Equals GetHashCode, System.Object.
588 22
,
.
Equals Complex,
:
class Complex
{
...
public override bool Equals(Object obj)
{
if (obj is Complex)
{
Complex compare = (Complex)obj;
return (this.Real == compare.Real) &&
(this.Imaginary == compare.Imaginary);
}
else
{
return false;
}
}
}
Equals Object.
, Complex-.
, Real Imaginary -
. ,
true, false.
Complex-, false.
Equals
:
public override bool Equals(Object obj)
{
Complex compare = obj as Complex;
if (compare != null)
{
return (this.Real == compare.Real) &&
(this.Imaginary == compare.Imaginary);
}
else
{
return false;
}
}
GetHashCode. ,
Object, , -
:
Class Complex
{
...
public override int GetHashCode()
{
return base.GetHashCode();
}
}
. ,
- .
Program.cs doWork
, :
static void doWork()
{
...
if (temp == first)
{
Console.WriteLine("Comparison: temp == first");
}
else
{
Console.WriteLine("Comparison: temp != first");
}
if (temp == temp)
{
Console.WriteLine("Comparison: temp == temp");
}
else
{
Console.WriteLine("Comparison: temp != temp");
}
}
temp == temp -
Comparison made to same variable; did you mean to compare to something
else? ( ; , -
- ?) -
, ,
, == , .
. , -
, , :
Comparison: temp != first
Comparison: temp == temp
.
, double:
class Example
{
public static void MyDoubleMethod(double parameter)
{
...
}
}
, MyDoubleMethod,
double,
. C# MyDoubleMethod
- ,
double. ,
int, ,
double.
. -
, , int-
double.
:
Example.MyDoubleMethod(42); // int double
,
, , .
int double double int int-
double-.
, double- -
int-:
class Example
{
public static void MyIntMethod(int parameter)
{
...
}
}
...
Example.MyIntMethod(42.0); //
591
double int ,
. (,
, MyIntMethod 42.5.
?) double
int, ( ):
Example.MyIntMethod((int)42.0);
, -
, (
),
OverflowException,
. C# -
,
. ,
.
, -
, ,
. -
, Hour-
int-:
struct Hour
{
...
public static implicit operator int (Hour from)
{
return from.value;
}
(public),
(static). , , -
( Hour), ,
,
operator ( int). ,
operator, .
,
.
592 22
implicit explicit.
Hour int, , , ,
C# ,
:
class Example
{
public static void MyOtherMethod(int parameter) { ... }
public static void Main()
{
Hour lunch = new Hour(12);
Example.MyOtherMethod(lunch); // Hour int
}
}
,
explicit, ,
.
Example.MyOtherMethod((int)lunch); // Hour int
, ?
, ,
, . -
. Hour
int Hour
int, , . , -
string Hour,
, -
Hours. ( 7 ,
Hour Hello, World?)
. , -
+ (Hour + Hour, Hour + int int + Hour)
Hour +
( Hour-) int Hour:
struct Hour
{
public Hour(int initialValue)
{
this.value = initialValue;
}
593
Hour int ( ), C# -
int Hour, + Hour:
void Example(Hour a, int b)
{
Hour eg1 = a + b; // b Hour
Hour eg2 = b + a; // b Hour
}
-
Complex. ,
int Complex. -
int Complex
, int -
.
. -
Complex- int,
. ,
.
Visual Studio 2015 Complex.
cs. , Complex, -
ToString ,
. int-,
Real.
Imaginary 0:
class Complex
{
...
public Complex(int real)
594 22
{
this.Real = real;
this.Imaginary = 0;
}
...
}
Complex :
class Complex
{
...
public static implicit operator Complex(int from)
{
return new Complex(from);
}
...
}
int Complex-, -
Complex
.
Complex , -
:
class Complex
{
...
public static explicit operator int(Complex from)
{
return from.Real;
}
...
}
Complex- Real.
.
Program.cs doWork
, :
static void doWork()
{
...
Console.WriteLine($"Current value of temp is {temp}");
if (temp == 2)
{
Console.WriteLine("Comparison after conversion: temp == 2");
}
else
{
Console.WriteLine("Comparison after conversion: temp != 2");
595
temp += 2;
Console.WriteLine($"Value after adding 2: temp = {temp}");
}
int Complex-. if Complex- int. -
, int Complex-,
== Complex. , 2 -
temp, int- 2 Complex-,
+ Complex.
doWork :
static void doWork()
{
...
int tempInt = temp;
Console.WriteLine($"Int value after conversion: tempInt == {tempInt}");
}
Complex- int-.
. ,
:
Cannot implicitly convert type 'ComplexNumbers.Complex' to 'int'. An explicit
conversion exists (are you missing a cast?)
, Complex- int-,
, -
.
, Complex- int-
, , :
int tempInt = (int)temp;
. ,
:
Current value of temp is (2 + 0i)
Comparison after conversion: temp == 2
Value after adding 2: temp = (4 + 0i)
Int value after conversion: tempInt == 4
-
.
,
, . -
, .
,
Visual Studio 2015 23 -
.
Visual Studio 2015, -
.
, .
- public static, -
- , operator, -
, -
. , :
class Complex
{
...
public static bool operator ==(Complex lhs, Complex rhs)
{
... // ==
}
...
}
- public static,
- implicit explicit, operator ,
- , -
,
, :
class Complex
{
...
public static implicit operator Complex(int from)
{
... // int
}
...
}
IV
Windows
C#
, C#.
, -
, Windows ,
,
. ,
, Windows UWP. UWP-
, , -
.
, . Windows 10
,
, ,
, -
. , Windows 10
,
-.
IV , -
UWP-. -
, .NET Framework.
UWP-,
,
.
23
, :
-
;
Task -
;
Parallel -
;
,
.
C# -
, .
,
. -
.
,
,
. -
. , Task-
,
.
, ? 599
,
?
.
.
, . -
, -
, ,
.
-
, ,
- , .
,
,
. 24
.
. -
,
-
, ,
. ,
, ,
, .
,
.
,
,
,
.
, -
, -
, .
-
800 1500 .
, 15 , .
600 23
23, 1000, -
48,
, DVD- -
.
500 1 , -
80, Windows 256
, -
100. ( DVD-
.) :
.
. 1965 , Intel,
Cramming More Components onto Integrated
Circuits (
), , -
, ,
, 1975 -
65000 .
, ,
, -
, ,
. (- ,
, , ,
, .) -
. , ,
-
,
, .
, ,
, . . -
,
, ,
.
-
.
3 . -
3.
-
Microsoft .NET Framework 601
, -
.
.
-
, .
- . 16,
32 64, -
, , -
. ,
,
.
C#?
, -
,
. .
-,
- .
, -
,
.
,
.
Microsoft .NET Framework
-
. , -
,
.
,
, , -
, .
,
.
?
, -
?
602 23
-
, ?
(, -
-)
, ?
,
?
-
. .
, Microsoft
Task ,
System.Threading.Tasks.
, -
. , ,
,
, .
, ThreadPool
Task , -
. Task- .
Task- ,
,
.
, -
.
-
. ,
, ,
:
, ,
-
.
,
,
,
.
WinRT ,
, -
.
,
ThreadPool, .
Task-, .
, -
. ThreadPool ,
,
(work-stealing algorithm).
ThreadPool .NET
Framework, .NET Framework 4.0 -
Task.
, , -
, .
. ,
,
. ,
-
, -
, .
-
. -
WinRT ,
(hill-climbing algorithm).
,
, ,
. WinRT
604 23
-
,
. ,
WinRT
, . -
,
-
, .
,
Task- Task-.
,
Action-. 20 -
, Action- ,
. Task- -
. Task-,
doWork:
Task task = new Task(doWork);
...
private void doWork()
{
//
...
}
Action , .
Task Action<object>, -
, ,
object. , , -
. :
Action<object> action;
action = doWorkWithObject;
object parameterData = ...;
Task task = new Task(action, parameterData);
...
private void doWorkWithObject(object o)
{
...
}
Task , -
Start:
Task task = new Task(...);
task.Start();
Microsoft .NET Framework 605
Start ,
TaskCreationOptions , -
.
TaskCreationOptions
Visual Studio
.NET Framework.
, Task
Run,
. Run Action-, -
( Task-),
. Task-.
:
Task task = Task.Run(() => doWork());
,
, , -
.
, , -
, .
Task- ContinueWith. ,
Task-, ,
Task- , ContinueWith.
, , Task-, -
. ,
ContinueWith, Task-.
Task-, doWork -
, doMoreWork ,
:
Task task = new Task(doWork);
task.Start();
Task newTask = task.ContinueWith(doMoreWork);
...
private void doWork()
{
//
...
}
...
private void doMoreWork(Task task)
{
// doWork
...
}
606 23
ContinueWith , , TaskConti
nuationOptions, , -
. TaskContinuationOptions , -
,
TaskCreationOptions. :
, -
, . Task
Wait, .
,
:
Task task2 = ...
task2.Start();
...
task2.Wait(); // , task2
Microsoft .NET Framework 607
,
WaitAll WaitAny Task.
params, Task-. WaitAll -
, WaitAny
. :
Task.WaitAll(task, task2); // , task task2
Task.WaitAny(task, task2); // , task,
// task2
Task
Task -
, ,
, ,
,
.
GraphDemo , -
Image .
, .
-
c . ,
. ,
,
.
GraphDemo
Microsoft Visual Studio 2015 GraphDemo, -
\Microsoft Press\VCSBS\Chapter 23\GraphDemo .
UWP.
MainPage.xaml
GraphDemo . -
Grid, ,
:
Image graphImage. -
, ;
Button () plotButton.
graphImage;
608 23
,
. UWP-
.
TextBlock duration. -
,
, .
MainPage.xaml,
MainPage.xaml.cs, .
WriteableBitmap (
Windows.UI.Xaml.Media.Imaging )
graphBitmap. WriteableBitmap-
pixelWidth pixelHeight :
public partial class MainPage : Window
{
// , pixelWidth pixelHeight
private int pixelWidth = 15000;
private int pixelHeight = 10000;
8 .
, pixelWidth pixelHeight,
OutOfMemoryException.
, -
, , -
.
MainPage:
public MainPage()
{
...
int dataSize = bytesPerPixel * pixelWidth * pixelHeight;
data = new byte[dataSize];
,
. -
WriteableBitmap-, pixelWidth pixelHeight.
, ,
Microsoft .NET Framework 609
: WriteableBitmap -
4, ,
-.
(- .)
WriteableBitmap- -
.
plotButton_Click:
private void plotButton_Click(object sender, RoutedEventArgs e)
{
Random rand = new Random();
redValue = (byte)rand.Next(0xFF);
greenValue = (byte)rand.Next(0xFF);
blueValue = (byte)rand.Next(0xFF);
Stopwatch watch = Stopwatch.StartNew();
generateGraphData(data);
, plotButton.
, ,
,
. (
.)
watch System.Diagnostics.Stopwatch -.
StopWatch .
StartNew, StopWatch,
StopWatch . StopWatch-
, ElapsedMilliseconds.
generateGraphData ,
WriteableBitmap.
.
generateGraphData
() TextBox duration.
, ,
WriteableBitmap- .
610 23
,
PixelBuffer
WriteableBitmap. Write
. Invalidate -
WriteableBitmap ,
, .
Source Image ,
.
Source WriteableBitmap.
generateGraphData:
private void generateGraphData(byte[] data)
{
int a = pixelWidth / 2;
int b = a * a;
int c = pixelHeight / 2;
-
. ( ,
.)
plotXY , -
.
x, , plotXY
: x-,
.
plotXY:
private void plotXY(byte[] data, int x, int y)
{
int pixelIndex = (x + y * pixelWidth) * bytesPerPixel;
data[pixelIndex] = blueValue;
Microsoft .NET Framework 611
data[pixelIndex + 1] = greenValue;
data[pixelIndex + 2] = redValue;
data[pixelIndex + 3] = 0xBF;
}
, -
x- y-, .
, ,
, 4. , ,
. 0xBF -
, -
. , ,
0xFF ( ),
.
,
.
Graph Demo, Plot Graph ( -
) . .
-
, ,
. ( ,
24.) .23.1. -
Duration(ms).
4907 . ,
, ,
.
, 8
, 2,4 .
-
,
.
Plot Graph ,
. , -
.
,
( 30 ). -
, Windows
.
,
.
612 23
. 23.1
,
.
.
(Performance) -
. ,
(More Details).
(CPU), (Change
Graph To), (Overall Utilization).
, .
-
.23.2.
Graph Demo
, ,
. -
, Graph Demo Plot Graph.
Microsoft .NET Framework 613
. 23.2
-
, Plot Graph.
16 , -
.
-
. , , ,
, , 5055%.
.23.3, ,
, 2530%. ,
, :
Visual Studio 2015 .
,
.
, , ,
.
, .
614 23
. 23.3
, Windows
-
. ,
, .
.
,
GraphDemo
( generateGraphData)
. , -
, ,
.
Visual Studio.
-
,
Microsoft .NET Framework 615
.
, . -
, .
,
. ,
.
Visual
Studio 2015 Community Edition .
Visual Studio ,
,
. Visual Studio
(.23.4).
. 23.4
616 23
, .
GraphDemo.
,
.
GraphDemo.
Plot Graph -
. ,
GraphDemo.
Visual Studio , -
,
(.23.5).
. 23.5
Microsoft .NET Framework 617
(
, , -
, Plot Graph)
. ,
.
98% plotButton_Click, 91,06% -
generateGraphData 35,93% plotXY.
(23,54%)
(coreclr.dll).
,
( -
) ,
.
GraphDemo.MainPage.generateGraphData.
, , -
, ,
(.23.6).
, for -
.
. 23.6
618 23
GraphDemo
Task-
Visual Studio 2015 MainPage.
xaml.cs. generateGraphData.
. -
for-, x
,
:
private void generateGraphData(byte[] data)
{
int a = pixelWidth / 2;
int b = a * a;
int c = pixelHeight / 2;
for (int x = 0; x < a; x ++)
{
int s = x * x;
double p = Math.Sqrt(b - s);
for (double i = -p; i < p; i += 3)
{
double r = Math.Sqrt(s + i * i) / a;
double q = (r - 1) * Math.Sin(24 * r);
double y = i / 3 + (q * c);
plotXY(data, (int)(-x + (pixelWidth / 2)), (int)(y +
(pixelHeight / 2)));
plotXY(data, (int)(x + (pixelWidth / 2)), (int)(y +
(pixelHeight / 2)));
}
}
}
, , -
, .
, ,
.
generateGraphData,
int- partitionStart partitionEnd, -
, :
private void generateGraphData(byte[] data, int partitionStart,
int partitionEnd)
{
...
}
generateGraphData for -
partitionStart partitionEnd, , -
:
Microsoft .NET Framework 619
MainPage.xaml.cs -
using:
using System.Threading.Tasks;
plotButton_Click ,
generateGraphData, -
, Task :
...
Stopwatch watch = Stopwatch.StartNew();
// generateGraphData(data);
Task first = Task.Run(() => generateGraphData(data, 0, pixelWidth / 4));
...
, -.
partitionStart partitionEnd , Task-
. ( -
, 0
pixelWidth / 2.)
, ,
Task:
...
Task first = Task.Run(() => generateGraphData(data, 0, pixelWidth / 4));
Task second = Task.Run(() => generateGraphData(data, pixelWidth / 4,
pixelWidth / 2));
...
Task- generateGraphData
pixelWidth / 4 pixelWidth / 2.
, ,
,
Task-:
Task second = Task.Run(() => generateGraphData(data, pixelWidth / 4,
pixelWidth / 2));
Task.WaitAll(first, second);
...
620 23
,
. ,
,
.
Graph Demo Plot Graph.
.
,
.
, , -
.
, , .
2858 , 40%.
, ,
, -
, ,
, .
,
.
. ,
.
Plot Graph 50%. ,
, -
. , , , ,
100% (.23.7).
,
,
, Task -,
plotButton_Click , , -
:
...
Task first = Task.Run(() => generateGraphData(data, 0, pixelWidth / 8));
Task second = Task.Run(() => generateGraphData(data, pixelWidth / 8,
pixelWidth / 4));
Task third = Task.Run(() => generateGraphData(data, pixelWidth / 4,
pixelWidth * 3 / 8));
Task fourth = Task.Run(() => generateGraphData(data, pixelWidth * 3 / 8,
pixelWidth / 2));
Task.WaitAll(first, second, third, fourth);
...
Microsoft .NET Framework 621
. 23.7
,
.
, ,
CLR, .
Parallel
Task -
, .
Task-,
. , :
-
.
, .
Parallel,
,
622 23
. , Parallel -
Task-
. Parallel
System.Threading.Tasks ,
,
. :
Parallel.For. C# -
for. , -
.
, :
, , -
.
,
, ,
. , , for,
:
for (int x = 0; x < 100; x++)
{
//
}
, ,
Parallel.For,
:
Parallel.For(0, 100, performLoopProcessing);
...
private void performLoopProcessing(int x)
{
//
}
Parallel.For,
, , -
, For,
ParallelLoopState-,
. ( ParallelLoopState
.)
Parallel.ForEach<T>. -
C# foreach. For, ForEach
, .
, - IEnumerable<T>,
Microsoft .NET Framework 623
, T. -
,
. ,
-
,
ForEach.
Parallel.Invoke.
.
( -), -
.
. , -
:
doWork();
doMoreWork();
doYetMoreWork();
, -
:
Parallel.Invoke(
doWork,
doMoreWork,
doYetMoreWork
);
, Parallel
, .
, Parallel.For , -
1000 , Parallel
1000 (
). Parallel -
,
.
,
,
. -
,
, ,
, .
GraphDemo
Parallel.
624 23
Parallel
GraphDemo
Visual Studio 2015 GraphDemo,
\Microsoft Press\VCSBS\Chapter 23\Parallel GraphDemo .
GraphDemo .
GraphDemo, ,
MainPage.xaml MainPage.xaml.cs,
.
using:
using System.Threading.Tasks;
generateGraphData. :
private void generateGraphData(byte[] data)
{
int a = pixelWidth / 2;
int b = a * a;
int c = pixelHeight / 2;
for, -
x.
, i,
- , i, -
. ( Parallel , -
.) ,
, , , -
, , ,
. ,
-
,
Microsoft .NET Framework 625
. ,
,
.
for
void- calculateData. int-
x data. , -
, a, b c, generateGraphData
calculateData. generateGraphData
calculateData (
):
private void generateGraphData(byte[] data)
{
for (int x = 0; x < a; x++)
{
}
}
private void calculateData(int x, byte[] data)
{
int a = pixelWidth / 2;
int b = a * a;
int c = pixelHeight / 2;
int s = x * x;
double p = Math.Sqrt(b - s);
for (double i = -p; i < p; i += 3)
{
double r = Math.Sqrt(s + i * i) / a;
double q = (r - 1) * Math.Sin(24 * r);
double y = i / 3 + (q * c);
plotXY(data, (int)(-x + (pixelWidth / 2)), (int)(y + (pixelHeight / 2)));
plotXY(data, (int)(x + (pixelWidth / 2)), (int)(y + (pixelHeight / 2)));
}
}
generateGraphData for , -
Parallel.For:
private void generateGraphData(byte[] data)
{
Parallel.For(0, pixelWidth / 2, x => calculateData(x, data));
}
for. 0 pixelWidth / 2 1 .
,
. Parallel.For ,
. , -
Parallel.For ,
626 23
. ,
. calculateData
, :
. -
-, ,
calculateData .
,
.
Graph Demo Plot Graph. Graph Demo
, , .
, .
,
, , Task-
(, , , -
). , ,
100% -
, , - (.23.8).
Visual Studio .
. 23.8
Microsoft .NET Framework 627
Parallel
, -
.NET Framework Microsoft
, Parallel ,
, ,
. Parallel
.
-
,
. ,
, , -
.
, .
,
. Parallel.
Invoke , , -
. Parallel.Invoke ,
,
.
Parallel
, .
, Parallel.For -
, ,
.
, , (
ParallelLoop, \Microsoft Press\
VCSBS\Chapter 23\ParallelLoop ):
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelLoop
{
class Program
{
private static int accumulator = 0;
{
AddToAccumulator(i);
}
Console.WriteLine($"Accumulator is {accumulator}");
}
0 99
AddToAccumulator.
accumulator , ,
accumulator, -
.
. 100.
,
for Main
Parallel.For:
, ,
AddToAccumulator, -
. ( -
, , , -
accumulator .) ,
AddToAccumulator, , -
,
. -
, AddToAccumulator -
.NET Framework
.
629
AddToAccumulator (
), :
private static void AddToAccumulator(int data)
{
if ((accumulator % 2) == 0)
{
accumulator += data;
Thread.Sleep(10); // 10
}
else
{
accumulator -= data;
}
}
Thread.Sleep
. , -
,
Parallel, ,
.
Parallel.For Parallel.ForEach
, -
.
Parallel.Invoke:
, -
.
, -
,
. ,
.
Task ,
, -
, .
.
,
630 23
. , ,
System.Threading.CancellationToken. ,
, IsCancellationRequested
true. , , -
.
true, , . ,
, , , ,
. -
, .
,
-
.
10, 1 .
CancellationToken System.
Threading.CancellationTokenSource Token .
CancellationToken-
, , -
. ,
Cancel CancellationTokenSource.
IsCancellationRequested CancellationToken, -
.
,
. initiateTasks
cancellationTokenSource CancellationToken-
, . ,
doWork. Cancel, -
, .
doWork IsCancellationRequested,
. true, ,
.
public class MyApplication
{
...
// ,
private void initiateTasks()
{
//
CancellationTokenSource cancellationTokenSource = new
CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
// doWork
Task myTask = Task.Run(() => doWork(cancellationToken));
631
...
if (...)
{
//
cancellationTokenSource.Cancel();
}
...
}
// ,
private void doWork(CancellationToken token)
{
...
// true,
if (token.IsCancellationRequested)
{
//
...
return;
}
// ,
...
}
}
: -
CancellationToken-.
CancellationTokenSource , -
IsCancellationRequested true
.
Register , -
( Action-) . -
Cancel
CancellationTokenSource, .
-
:
...
cancellationToken,Register(doAdditionalWork);
...
private void doAdditionalWork()
{
//
}
GraphDemo.
632 23
GraphDemo
Visual Studio 2015 GraphDemo,
\Microsoft Press\VCSBS\Chapter 23\GraphDemo With Cancellation
.
GraphDemo ,
. cancelButton, -
,
.
GraphDemo
MainPage.xaml, .
Cancel ().
MainPage.xaml.cs. Button_Click.
, Cancel ().
.
using:
using System.Threading;
,
.
MainPage CancellationTokenSource
tokenSource , ,
null:
public sealed partial class MainPage : Page
{
...
private byte redValue, greenValue, blueValue;
private CancellationTokenSource tokenSource = null;
...
}
generateGraphData
CancellationToken token, -
:
private void generateGraphData(byte[] data, int partitionStart,
int partitionEnd, CancellationToken token)
{
...
}
633
for generateGraphData
, , .
, ,
:
private void generateGraphData(byte[] data, int partitionStart,
int partitionEnd, CancellationToken token)
{
int a = pixelWidth / 2;
int b = a * a;
int c = pixelHeight / 2;
double r = Math.Sqrt(s + i * i) / a;
double q = (r - 1) * Math.Sin(24 * r);
double y = i / 3 + (q * c);
plotXY(data, (int)(-x + (pixelWidth / 2)), (int)(y +
(pixelHeight / 2)));
plotXY(data, (int)(x + (pixelWidth / 2)), (int)(y +
(pixelHeight / 2)));
}
}
}
plotButton_Click ,
, tokenSource
CancellationToken- token:
, ,
generateGraphData token:
634 23
...
Task first = Task.Run(() => generateGraphData(data, 0, pixelWidth / 4,
token));
Task second = Task.Run(() => generateGraphData(data, pixelWidth / 4,
pixelWidth / 2, token));
...
plotButton_Click
async, :
plotButton_Click Task.WaitAll,
,
, , -
await:
...
// Task.WaitAll(first, second);
await first;
await second;
duration.Text = string.Format(...);
...
, ,
Windows. -
,
, ,
,
(
). Task.WaitAll
Cancel
, Cancel ,
Plot Graph,
. ,
, Plot Graph, -
,
plotButton_Click
.
,
await. , -
async.
635
.
, , -
. await -
.
, ,
, ,
TextBlock duration. await ,
, , await
.
async await -
24.
cancelButton_Click. ,
:
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (tokenSource != null)
{
tokenSource.Cancel();
}
}
tokenSource. -
, Cancel.
,
.
GraphDemo Plot Graph ,
, . , -
, .
, generateGraphData.
Plot Graph ,
Cancel.
Cancel , -
,
, .
,
(.23.9). ( ,
- , ,
Cancel.)
Visual Studio .
636 23
. 23.9
Status Task, ,
. Status -
System.Threading.Tasks.TaskStatus. ,
, (
).
Created. . ,
.
WaitingToRun. ,
.
Running. .
RanToCompletion. - -
.
Canceled. , ,
.
Faulted. -
.
, .
637
FOR LOOP
Parallel.For Parallel.ForEach
Task-. , -
, .NET Framework
.
Parallel.For Parallel.ForEach ,
ParallelLoopState. , -
, ParallelLoopState.
Parallel ParallelLoopState- -
. Parallel
. Stop ,
Parallel ,
, .
Parallel.For, doLoopWork.
doLoopWork : 600,
Stop ParallelLoopState. ,
Parallel.For . (
.)
, Parallel.For -
. ,
600 , 599
. , -
600:
Parallel.For(0, 1000, doLoopWork);
...
private void doLoopWork(int i, ParallelLoopState p)
{
...
if (i > 600)
{
p.Stop();
}
}
Visual Studio MainPage.xaml.
XAML- MainPage , -
, </Grid>-:
<Image x:Name="graphImage" Grid.Column="1" Stretch="Fill" />
</Grid>
<TextBlock x:Name="messages" Grid.Row="4" FontSize="18"
HorizontalAlignment="Left"/>
</Grid>
</Page>
638 23
TextBlock messages.
MainPage.xaml.cs plotButton_
Click . , .
,
,
messages TextBlock,
.
private async void plotButton_Click(object sender, RoutedEventArgs e)
{
...
await first;
await second;
.
GraphDemo Plot Graph, Cancel.
, (
),
RanToCompletion.
. 23.10
IfCancellationRequested. IsCancellationRequested
: true,
OperationCanceledException , -
.
, , -
, . -
,
Faulted. , OperationCanceledException.
Canceled, -
. OperationCanceledException,
?
. -
, OperationCanceledException
, , ,
, . ,
. -
, ,
- .
. ,
, GraphDemo.
640 23
generateGraphData ( -
), Run:
tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
...
Task first = Task.Run(() => generateGraphData(data, 0, pixelWidth / 4, token),
token);
, , ,
OperationCanceledException , , ,
CancellationToken. -
,
Canceled. await,
OperationCanceledException. -
.
OperationCanceledException
Visual Studio ,
MainPage.xaml.cs. plotButton_Click -
, ,
CancellationToken-
Run ( generateGraphData):
private async void plotButton_Click(object sender, RoutedEventArgs e)
{
...
tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
...
Task first = Task.Run(() => generateGraphData(data, 0, pixelWidth / 4,
token), token);
Task second = Task.Run(() => generateGraphData(data, pixelWidth / 4,
pixelWidth / 2, token), token);
...
}
, ,
, try .
catch, OperationCanceledException. -
TextBlock
641
duration ,
Message .
:
private async void plotButton_Click(object sender, RoutedEventArgs e)
{
...
try
{
await first;
await second;
generateGraphData if,
IsCancellationRequested CancellationToken, -
, ,
ThrowIfCancellationRequested:
private void generateGraphData(byte[] data, int partitionStart,
int partitionEnd, CancellationToken token)
{
...
for (int x = partitionStart; x < partitionEnd; x++);
{
...
for (double i = -p; i < p; i += 3)
{
//if (token.IsCancellationRequested)
//{
// return;
//}
token.ThrowIfCancellationRequested();
...
}
}
...
}
-
. Common
642 23
. 23.11
, Visual Studio
OperationCanceledException,
.
.
Graph Demo Plot Graph, -
,
RanToCompletion .
Plot Graph Cancel.
,
Canceled, TextBox
duration The operation was canceled, -
.
, (.23.12).
Visual Studio .
-
.
,
OK.
643
. 23.12
AGGREGATEEXCEPTION
, -
.
, ,
, -
, , -
. -
, .
,
OperationCanceledException, .
, ,
.
,
.
Task ( Wait Task.
WaitAll Task.WaitAny), , , -
, ,
AggregateException.
.
.
644 23
AggregateException, -
. AggregateException
Handle. Func<Exception,
bool>, ,
Exception . Handle
AggregateException
, .
.
, true. ,
false. Handle , -
AggregateException.
.
, -
AggregateException.
DivideByZeroException
Division by zero occurred
IndexOutOfRangeException
Array index out of bounds.
.
private bool handleException(Exception e)
{
if (e is DivideByZeroException)
{
displayErrorMessage("Division by zero occurred");
return true;
}
if (e is IndexOutOfRangeException)
{
displayErrorMessage("Array index out of bounds");
return true;
}
return false;
}
Task, -
AggregateException handleException:
try
{
Task first = Task.Run(...);
Task second = Task.Run(...);
Task.WaitAll(first, second);
}
catch (AggregateException ae)
{
ae.Handle(handleException);
}
645
DivideByZeroException
IndexOutOfRangeException, handleException -
, .
AggregateException .
, . ,
CLR OperationCanceledException, -
, -
await.
Task, TaskCanceledException,
,
AggregateException.
,
, , -
ContinueWith TaskContinuationOptions-
. , ,
doWork. , ContinueWith ,
, doCancellationWork.
. ,
.
Task task = new Task(doWork);
task.ContinueWith(doCancellationWork, TaskContinuationOptions.OnlyOnCanceled);
task.Start();
...
private void doWork()
{
//
...
}
...
private void doCancellationWork(Task task)
{
// , doWork
...
}
, TaskContinuationOptions.OnlyOnFaulted,
, -
, .
646 23
, , -
-
. , Task
.
Parallel
, ,
.
, -
.
,
Visual Studio 2015 24.
Visual Studio 2015, -
.
, .
, -
Run Task:
Task task = Task.Run(() => doWork());
...
private void doWork()
{
//
...
}
Task-, -
, Start:
Task task = new Task(doWork);
task.Start();
- Wait Task:
Task task = ...;
...
task.Wait();
await ( async-):
await task;
647
- WaitAll Task -
, :
Task task1 = ...;
Task task2 = ...;
Task task3 = ...;
Task task4 = ...;
...
Task.WaitAll(task1, task2, task3, task4);
ContinueWith
- , :
, Task task = new Task(doWork);
- task.ContinueWith(doMoreWork,
TaskContinuationOptions.NotOnFaulted);
- -
- Parallel.For Parallel.ForEach:
Parallel.For(0, 100, performLoopProcessing);
...
private void performLoopProcessing(int x)
- {
//
}
-
Parallel.
Invoke:
Parallel.Invoke(
doWork,
doMoreWork,
doYetMoreWork
);
- AggregateException.
, Handle ,
- AggregateException.
, -
true, , false:
try
{
Task task = Task.Run(...);
task.Wait();
...
}
catch (AggregateException ae)
{
ae.Handle(handleException);
}
648 23
...
private bool handleException(Exception e)
{
if (e is TaskCanceledException)
{
...
return true;
}
else
{
return false;
}
}
CancellationTokenSource-
CancellationToken- , .
ThrowIfCancellationRequested,
CancellationToken,
OperationCanceledException -
:
private void generateGraphData(...,
CancellationToken
token)
{
...
token.ThrowIfCancellationRequested();
...
}
24
, :
,
,
- ;
, ,
LINQ-, ;
-
.
23 -
Task
,
. ,
-
, -
.
, Windows
,
,
. ,
,
(, , , -
- ,
650 24
-),
,
, , ,
. :
,
.
, , -
. , 21 ,
, ,
, , ,
C# (Language-Integrated Query (LINQ)). -
LINQ- ,
.
, ,
, LINQ- .
, ,
,
, . -
Microsoft .NET Framework LINQ -
, Parallel LINQ,
PLINQ. .
, ,
. ,
,
-
. -
, ,
,
,
, , -
.
, ,
.NET Framework . C#
async await, -
,
( ),
.
651
,
,
- . -
, -
,
.
,
, 12 . , ,
,
. ,
, ,
-. -
, , -
, -,
.
- , -
.
, ,
.
, -
- ,
- (Synchronous I/O anti-pattern) -
Microsoft Patterns & Practices https://github.com/
mspnp/performance-optimization/tree/master/SynchronousIO.
,
Task-. : -
Start Run, Task,
(common language runtime (CLR))
-
, -
.
.
,
.
,
Wait-, Task-.
, , .
, , -
. .NET Framework
652 24
, -
.
, .
Task- -
,
,
. -
, , ,
, ,
TextBox:
private void slowMethod()
{
doFirstLongRunningOperation();
doSecondLongRunningOperation();
doThirdLongRunningOperation();
message.Text = "Processing Completed";
}
slowMethod - -
(, Click
),
.
slowMethod Task-
, doFirstLongRunningOperation
,
doSecondLongRunningOperation doThirdLongRunningOperation:
task.Start();
message.Text = "Processing Completed"; // ?
}
,
. , doSecond
LongRunningOperation doThirdLongRunningOperation ,
(
Task-, ). -
: TextBox?.
, :
Start Task, -
, , ,
.
, .
. ,
:
private void slowMethod()
{
Task task = new Task(doFirstLongRunningOperation);
task.ContinueWith(doSecondLongRunningOperation);
task.ContinueWith(doThirdLongRunningOperation);
task.Start();
task.Wait();
message.Text = "Processing Completed";
}
Wait , slowMethod,
Task.
- Wait -
.
654 24
,
-
doThirdLongRunningOperation, Wait
.
, ( , -
Task- ,
t):
, .
, , -
System.Exception
, ,
: The application called an interface that was marshaled for a
different thread. , -
,
TextBox
, , Task-. -
Dispatcher-.
,
RunAsync
. Action-
, . ,
Dispatcher- RunAsync, ,
, ,
,
slowMethod:
,
. (), -
(, RunAsync).
Dispatcher
RunAsync - Microsoft https://msdn.
microsoft.com/library/windows.ui.core.coredispatcher.runasync.
:
async await C# ,
, -
. ,
Dispatcher-
. :
async , ,
;
await ,
.
slowMethod, -
async await :
private async void slowMethod()
{
await doFirstLongRunningOperation();
await doSecondLongRunningOperation();
await doThirdLongRunningOperation();
message.Text = "Processing Complete";
}
,
async await.
, C#.
, async, -
await, ,
, , ,
async-. ,
, . ,
, async-, ,
,
, , ,
Dispatcher-.
656 24
, -
.
async ,
. -
,
. ,
, .
await , C# -
. await
, . ,
GetAwaiter, ,
-
. C# ,
.
await async.
async-
( await, ).
await , ,
, Task . ,
doFirstLongRunningOperation ,
doSecondLongRunningOperation doThirdLongRunningOperation. ,
-
Task- Task-.
doFirstLongRunningOperation:
private Task doFirstLongRunningOperation()
{
Task t = Task.Run(() => { /* */ });
return t;
}
, ,
doFirstLongRunningOperation,
. ,
(Task-) , 23.
Task- ?
private Task doFirstLongRunningOperation()
{
Task first = Task.Run(() => { /* */ });
Task second = Task.Run(() => { /* */ });
return ...; // , first second?
}
657
, , await, ,
,
, ,
. , async-,
, (
, -
). , doFirstLongRunningOperation
first second, -
await , first,
, second, -
async .
, -
,
(, ,
).
await async-, -
Task-, .
.
, async-
await : This async method lacks await
operators and will run synchronously.
async ,
, -
await.
GraphDemo
23 ,
.
658 24
GraphDemo
Microsoft Visual Studio 2015 GraphDemo, -
\Microsoft Press\VCSBS\Chapter 24\GraphDemo .
MainPage.xaml -
MainPage.xaml.cs.
MainPage plotButton_Click.
:
private void plotButton_Click(object sender, RoutedEventArgs e)
{
Random rand = new Random();
redValue = (byte)rand.Next(0xFF);
greenValue = (byte)rand.Next(0xFF);
blueValue = (byte)rand.Next(0xFF);
try
{
generateGraphData(data, 0, pixelWidth / 2, token);
duration.Text = $"Duration (ms): {watch.ElapsedMilliseconds}";
}
catch (OperationCanceledException oce)
{
duration.Text = oce.Message;
}
Stream pixelStream = graphBitmap.PixelBuffer.AsStream();
pixelStream.Seek(0, SeekOrigin.Begin);
pixelStream.Write(data, 0, data.Length);
graphBitmap.Invalidate();
graphImage.Source = graphBitmap;
}
.
generateGraphData
, Task , -
, .
23 -
pixelWidth pixelHeight, ,
, .
. GraphDemo
Plot Graph. Cancel.
659
, -
. ,
plotButton_Click , ,
, .
Visual Studio .
, MainPage,
generateGraphData generateGraphDataAsync.
,
generateGraphData, void Task-. -
async, :
private async Task generateGraphDataAsync(byte[] data,
int partitionStart, int partitionEnd,
CancellationToken token)
{
}
Async.
generateGraphDataAsync , -
:
private async Task generateGraphDataAsync(byte[] data, int partitionStart, int
partitionEnd, CancellationToken token)
{
Task task = Task.Run(() => generateGraphData(data, partitionStart,
partitionEnd,token));
await task;
}
Task-, generateGraphData -
await Task-. -
, await,
, .
plotButton_Click ,
, , async:
private async void plotButton_Click(object sender, RoutedEventArgs e)
{
...
}
try plotButton_Click ,
,
generateGraphDataAsync :
660 24
try
{
await generateGraphDataAsync(data, 0, pixelWidth / 2, token);
duration.Text = $"Duration (ms): {watch.ElapsedMilliseconds}");
}
...
-
. Common Language
Runtime Exceptions. Common Language
Runtime Exceptions ,
.
. GraphDemo
Plot Graph , -
.
Plot Graph, Cancel.
.
, TextBlock
duration : The operation
was cancelled (.24.1).
Visual Studio .
. 24.1
661
-
Task-, .
, .
- Task<TResult>, , TResult,
.
Task<TResult> ,
Task-. , -
. , calculateValue,
, .
Task<int>.
, , Result,
Task<int>-.
, Result
. , -
: Result
, :
Task<int> calculateValueTask = Task.Run(() => calculateValue(...));
...
int calculatedData = calculateValueTask.Result; //
// calculateValueTask
...
private int calculateValue(...)
{
int someValue;
// someValue
...
return someValue;
}
- Task<TResult>
, .
, void-
Task-. , ,
,
calculateValue, Task<TResult>:
,
Task<int>, return int. -
, async-
Task-,
, generateResultTask.Result;.
int,
Task<int>.
, , -
await:
int result = await calculateValueAsync(...);
Task- -
calculateValueAsync result.
,
, async await
. .
async, , -
. ,
, .
await ,
,
. , ,
. ,
, ,
-
.
await
Wait,
, .
, await ,
,
. , .
,
, , -
ConfigureAwait(false). -
, -
.
663
ConfigureAwait(false) , ,
await, .
ConfigureAwait(false) -
await , ,
, .
, Text -
, ,
, , -
: The application called an interface that was
marshaled for a different thread.
private async void slowMethod()
{
await doFirstLongRunningOperation().ConfigureAwait(false);
await doSecondLongRunningOperation().ConfigureAwait(false);
await doThirdLongRunningOperation().ConfigureAwait(false);
message.Text = "Processing Complete";
}
,
,
-
. :
private async void myMethod()
{
var data = generateResult();
...
message.Text = $"result: {data.Result}";
}
generateResult .
myMethod ,
generateResult, data.Result. -
data , Result
, ,
generateResult.
, , ,
generateResult, ,
( ),
664 24
. myMethod -
, generateResult,
generateResult ,
myMethod.
await -
, generateResult.
:
private async void myMethod()
{
var data = generateResult();
...
message.Text = $"result: {await data}";
}
API-
WindowsRuntime
Windows 8
, -
WinRT , ,
50 , -
API-.
. ,
MessageDialog.
ShowAsync:
using Windows.UI.Popups;
...
MessageDialog dlg = new MessageDialog("Message to user");
await dlg.ShowAsync();
MessageDialog , -
Close (),
.
( Close,
),
(,
), .
MessageDialog ShowAsync,
,
dlg.ShowAsync() await.
-
FileOpenPicker , 5
665
. FileOpenPicker -
,
. MessageDialog,
,
.
, FileOpenPicker , -
,
:
using Windows.Storage;
using Windows.Storage.Pickers;
...
FileOpenPicker fp = new FileOpenPicker();
fp.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
fp.ViewMode = PickerViewMode.List;
fp.FileTypeFilter.Add("*");
StorageFile file = await fp.PickSingleFileAsync();
, PickSingle
FileAsync. , -
. (
FileOpenPicker PickMultipleFilesAsync,
.) ,
, Task<StorageFile>, await
StorageFile. StorageFile
,
. , -
.
, PickSingleFileAsync
IAsyncOperation<StorageFile>. WinRT
Task- .NET Framework
; IAsyncOperation Task. -
C#,
Task-, , -
WinRT.
-
-, StorageFile
, ,
. , 5,
, FileOpenPicker-,
:
StorageFile file = await fp.PickSingleFileAsync();
...
var fileStream = await file.OpenAsync(FileAccessMode.Read);
666 24
, , -
, ,
. ,
,
, .
. ,
WriteableBitmap,
AsStream Stream (
). Write:
...
Stream pixelStream = graphBitmap.PixelBuffer.AsStream();
pixelStream.Seek(0, SeekOrigin.Begin);
pixelStream.Write(data, 0, data.Length);
...
pixelWidth pixelHeight
, , ,
570 (15000100004 ), Write
. -
, WriteAsync:
await pixelStream.WriteAsync(data, 0, data.Length);
, Windows,
,
.
IASYNCRESULT
.NET FRAMEWORK
.NET Framework , -
Task .NET Framework 4.0. ,
, Microsoft
IAsyncResult AsyncCallback.
, ,
,
.NET Framework
: , , -
,
(BeginOperationName) (EndOperationName), -
. , MemoryStream
System.IO Write
,
BeginWrite EndWrite .
667
BeginWrite , ,
, -
,
AsyncCallback-.
,
, EndWrite. -
:
...
Byte[] buffer = ...; // MemoryStream
MemoryStream ms = new MemoryStream();
AsyncCallback callback = new AsyncCallback(handleWriteCompleted);
ms.BeginWrite(buffer, 0, buffer.Length, callback, ms);
...
private void handleWriteCompleted(IAsyncResult ar)
{
MemoryStream ms = ar.AsyncState as MemoryStream;
... //
ms.EndWrite(ar);
}
(handleWriteCompleted) IAsync
Result-, -
.
, ,
, BeginOperationName.
MemoryStream.
-
,
. ,
.
Task-
FromAsync, TaskFactory.
BeginOperationName EndOperationName , -
, Task-.
AsyncCallback-,
FromAsync. , ,
, :
...
Byte[] buffer = ...;
MemoryStream s = new MemoryStream();
Task t = Task<int>.Factory.FromAsync(s.Beginwrite, s.EndWrite, buffer, 0,
buffer.Length, null);
t.Start();
await t;
...
, -
, ,
.NET Framework.
668 24
PLINQ
, ,
. , -
.
LINQ -
,
. PLINQ LINQ- ,
Task-,
.
PLINQ -
, ,
. ,
, ,
. PLINQ ,
, ,
, , -
, .
PLINQ .
LINQ- PLINQ-
AsParallel. ParallelQuery-,
, ,
LINQ-,
join where. LINQ-
LINQ- -
, .
, AsParallel . ,
, LINQ-
, .
PLINQ ,
, .
.
PLINQ
. LINQ-, -
,
PLINQ 669
. -
, -
.
,
.
.
, .
, , -
, IList<T>.
LINQ-
Program.cs PLINQ,
. ,
, . . Program -
Test1 Test2, ,
. Main
.
: LINQ- (
),
.
, .
Test1. ,
, 0
200. ,
.
TO DO LINQ-,
:
// TO DO: LINQ-, 100
var over100 = from n in numbers
where TestIfTrue(n > 100)
select n;
LINQ-
100. n > 100 -
, , -
, TestIfTrue,
, SpinWait. SpinWait
670 24
-
, ,
( ). TestIfTrue
:
public static bool TestIfTrue(bool expr)
{
Thread.SpinWait(1000);
return expr;
}
Test1 TO DO ,
:
// TO DO: Run the LINQ query, and save the results in a List<int> object
List<int> numbersOver100 = new List<int>(over100);
, LINQ- ,
,
. List<int>
over100.
Test1 TO DO , -
:
// TO DO: Display the results
Console.WriteLine($"There are {numbersOver100.Count} numbers over 100");
.
Test1 , -
100.
.
, , 100,
( ,
). , -
Visual Studio.
, , LINQ-, -
,
. ,
, , LINQ-,
AsParallel numbers:
var over100 = from n in numbers.AsParallel()
where TestIfTrue(n > 100)
select n;
PLINQ 671
-
, ,
, .
-
.
. ,
, Test1 , , ,
, , .
.
( -
), , 4045%.
, (
10,3 2,8 ).
Visual Studio.
, -
LINQ-.
, -
, , ,
. .
.
LINQ-,
.
, .
LINQ-,
Data.cs, -
CustomersInMemory.
Customers.
Customers ,
. -
, ,
, . -
, , ,
, , .
OrdersInMemory. CustomersInMemory,
, Orders.
,
, .
672 24
OrderInfo. : ,
, . -
OrderInfo , Customers
Orders, LINQ-.
Program.cs Program
Test2 . LINQ-,
Customers Orders -
, .
OrderInfo.
try- TO DO , -
:
// TO DO: Create a LINQ query that retrieves customers and orders from arrays
// Store each row returned in an OrderInfo object
var orderInfoQuery = from c in CustomersInMemory.Customers
join o in OrdersInMemory.Orders
on c.Split(',')[0] equals o.Split(',')[1]
select new OrderInfo
{
CustomerID = c.Split(',')[0],
CompanyName = c.Split(',')[1],
OrderID = Convert.ToInt32(o.Split(',')[0]),
OrderDate = Convert.ToDateTime(o.Split(',')[2],
new CultureInfo("en-US"))
};
LINQ-. ,
Split, String. ,
. ,
United States English, , OrderInfo-,
DateTime, United States English.
,
.
.
Test2 TO DO , -
:
// TO DO: Run the LINQ query, and save the results in a List<OrderInfo> object
List<OrderInfo> orderInfo = new List<OrderInfo>(orderInfoQuery);
orderInfo.
TO DO ,
:
// TO DO: Display the results
Console.WriteLine($"There are {orderInfo.Count} orders");
PLINQ 673
Main , Test1, -
, Test2,
:
static void Main(string[] args)
{
// Test1();
Test2();
}
.
, Test2 830 , -
.
, Visual Studio.
Test2 , , -
LINQ- AsParallel Customers
Orders:
var orderInfoQuery = from c in CustomersInMemory.Customers.AsParallel()
join o in OrdersInMemory.Orders.AsParallel()
on c.Split(',')[0] equals o.Split(',')[1]
select new OrderInfo
{
CustomerID = c.Split(',')[0],
CompanyName = c.Split(',')[1],
OrderID = Convert.ToInt32(o.Split(',')[0]),
OrderDate = Convert.ToDateTime(o.Split(',')[2],
New CultureInfo("en-US"))
};
IEnumerable ParallelQuery. ,
AsParallel AsParallel
. ,
.
. , -
Test2 , .
, PLINQ
.
Visual Studio.
AsParallel PLINQ. , PLINQ
, ,
674 24
. , -
, ,
PLINQ.
, -
. ,
-
PLINQ
.
PLINQ-
LINQ-, PLINQ- .
CancellationToken- CancellationTokenSource -
WithCancellation ,
ParallelQuery:
WithCancellation .
. CancellationTokenSource, -
CancellationToken, ,
OperationCanceledException.
PLINQ -
. ,
.
.NET Framework ,
, -
. ,
,
. -
, .
,
.
675
Task , -
,
. ,
, ,
.
,
, , .
,
.
Microsoft:
, ,
.
. ,
, , .
, (
ParallelTest , 24),
( ) :
using System;
using System.Threading;
class Program
{
private const int NUMELEMENTS = 10;
SerialTest ( ) -
,
, -
. doAdditionalProcessing
doMoreAdditionalProcessing -
,
. :
Element 0 has value 0
Element 1 has value 1
Element 2 has value 2
Element 3 has value 3
Element 4 has value 4
Element 5 has value 5
Element 6 has value 6
Element 7 has value 7
Element 8 has value 8
Element 9 has value 9
ParallelTest. -
SerialTest, ,
data
Parallel.For. -, -
, for SerialTest:
using System.Threading.Tasks;
...
j = i;
doAdditionalProcessing();
data[i] = j;
doMoreAdditionalProcessing();
});
, ParallelTest ,
SerialTest, , -
. ,
. , -
ParallelTest:
Element 0 has value 1
Element 1 has value 1
Element 2 has value 4
Element 3 has value 8
Element 4 has value 4
Element 5 has value 1
Element 6 has value 4
Element 7 has value 8
Element 8 has value 8
Element 9 has value 9
, data,
, SerialTest. ,
ParallelTest
.
Parallel.For, ,
. - :
j = i;
doAdditionalProcessing();
data[i] = j;
doMoreAdditionalProcessing();
. i
( , , )
j, j
data, i. i 5, j -
5, j data[5].
j
doAdditionalProcessing.
678 24
, -
.
,
Parallel.For, j .
, , j,
data[5], , -
, .
,
,
-
-
. ,
.
j
. j, -
, ,
j .
,
, .
.
, -
, C#
lock. lock
:
object myLockObject = new object();
...
lock (myLockObject)
{
// ,
...
}
lock -
( - ,
), ,
. , ,
, lock.
.
, .
679
lock
,
. System.Threading
,
. , -
.
,
. , -
,
, , -
, ,
-,
, .
. -
,
Visual Studio 2015.
.NET Framework
. -
, System.
Threading.
. , ,
, -
.
,
, ,
, , . -
, ,
,
Visual Studio 2015.
ManualResetEventSlim. ManualResetEventSlim
,
.
ManualResetEventSlim -
: (true) (false). ManualReset
EventSlim- .
680 24
, ManualResetEventSlim- ,
Wait. ManualResetEventSlim -
, Wait .
ManualResetEventSlim-
Set. , -
ManualResetEventSlim-,
. Reset ManualResetEventSlim-,
.
SemaphoreSlim. SemaphoreSlim
.
SemaphoreSlim (
) . -
SemaphoreSlim- . ,
, Wait.
SemaphoreSlim ,
, -
. ,
SemaphoreSlim- Release.
.
Wait
SemaphoreSlim- , ,
Release.
SemaphoreSlim CurrentCount,
, Wait
.
CountdownEvent. CountdownEvent
.
CountdownEvent-, -
( ).
Wait CountdownEvent, -
, . Wait
CountdownEvent- , , ,
Signal. CountdownEvent-
,
.
CountdownEvent- , -
, Reset,
, AddCount.
CurrentCount ,
Wait.
681
ReaderWriterLockSlim. ReaderWriterLockSlim -
,
. ,
( ) ,
, , -
.
, , EnterReadLock, -
ReaderWriterLockSlim.
. ,
ExitReadLock, .
,
.
,
EnterWriteLock ReaderWriterLockSlim-, -
.
, EnterWriteLock -
, .
,
ExitWriteLock, .
ReaderWriterLockSlim
. ,
,
.
, ,
EnterReadLock, , -
, .
Barrier. Barrier,
,
.
, , ,
.
Barrier,
, .
,
Barrier. -
AddParticipant
RemoveParticipant. ,
SignalAndWait, Barrier-,
682 24
Barrier-. -
, .
, ,
- Barrier, -
.
Barrier ParticipantCount, -
, ParticipantsRemaining, -
, SignalAndWait
.
Barrier .
, , .
Barrier-. -
, .
, ManualResetEventSlim, SemaphoreSlim, CountdownEvent Barrier,
, , 23. -
-
CancellationToken , ,
CancellationTokenSource. Cancel Cancella
tionTokenSource, ,
CancellationToken, , -
OperationCanceledException (, , -
AggregateException ).
Wait SemaphoreSlim -
, . , -
, OperationCanceledException.
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
...
// ,
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(3);
...
// OperationCanceledException,
// Cancel cancellationTokenSource
try
{
semaphoreSlim.Wait(cancellationToken);
}
catch (OperationCanceledException e)
{
...
}
683
-
.
, .NET Framework,
, , -
, ,
,
.
,
.NET Framework
,
System.Collections.Concurrent -
.
.
ConcurrentBag<T>. -
. (Add),
(TryTake) (TryPeek) . -
. ,
foreach.
ConcurrentDictionary<TKey, TValue>.
- Dictionary<TKey,
TValue>, 18 . -
TryAdd, ContainsKey, TryGetValue, TryRemove TryUpdate,
,
, .
ConcurrentQueue<T>. -
- Queue<T>, 18.
Enqueue, TryDequeue TryPeek, -
, .
ConcurrentStack<T>.
- Stack<T>, 18. -
Push, TryPop TryPeek,
, ,
.
-
,
, .
-
, .
684 24
,
.
,
-
.
,
,
, ,
, .
-
. r
, ,
2r (.24.2).
. 24.2
S :
S = (2r)(2r)
S = 4rr.
C :
C = rr.
685
,
rr = C/
rr = S/4.
, :
S/4 = C/.
:
= 4C/S.
,
C S. .
,
. ,
, , , (
), C/S. -
.
, ?
, -
(0,0). ,
, (r,r) (+r, +r). -
, (x, y) ,
. d
(xx + yy). d
r , , .24.3, -
(x, y) .
, ,
,
0 r.
.
-
. -
, , , . ,
, .
Visual Studio 2015 CalculatePI,
\Microsoft Press\VCSBS\Chapter 24\CalculatePI .
686 24
. 24.3
Program.cs CalculatePI, -
, .
. .
Main,
:
static void Main(string[] args)
{
double pi = SerialPI();
Console.WriteLine($"Geometric approximation of PI calculated serially: {pi}");
Console.WriteLine();
// pi = ParallelPI();
// Console.WriteLine($"Geometric approximation of PI calculated in
// parallel: {pi}");
}
SerialPI, -
, .
. ,
, ParallelPI, -
,
. ,
, SerialPI.
SerialPI.
687
try
{
// TO DO:
return 0;
}
finally
{
long milliseconds = timer.ElapsedMilliseconds;
Console.WriteLine($"SerialPI complete: Duration: {milliseconds} ms",);
Console.WriteLine(
$"Points in pointsList: {pointsList.Count}. Points within circle:
{numPointsInCircle}");
}
}
-
.
NUMPOINTS Program. -
,
, .
, NUMPOINTS.
,
OutOfMemoryException, .
pointsList,
List<double>. -
random. Random-,
,
. (
, .) , -
,
SEED Program.
pointsList,
, numPointsInCircle. -
Program RADIUS.
-
ParallelPI, Stopwatch-
timer, , , -
. , ,
688 24
. ,
, ,
pointsList, , .
try- , -
.
try- return, -
.
try- for ,
:
try
{
for (int points = 0; points < NUMPOINTS; points++)
{
int xCoord = random.Next(RADIUS);
int yCoord = random.Next(RADIUS);
double distanceFromOrigin = Math.Sqrt(xCoord * xCoord + yCoord * yCoord);
pointsList.Add(distanceFromOrigin);
doAdditionalProcessing();
}
}
0
RADIUS xCoord yCoord.
,
pointsList.
, -
, ,
,
. ,
, doAdditionalProcessing. ,
.
,
, -
, -
, :
SPINWAITS ,
Program.
try
{
for (int points = 0; points < NUMPOINTS; points++)
{
...
}
pointsList
.
, numPointsInCircle
. numPointsInCircle -
, .
try foreach , -
:
try
{
for (int points = 0; points < NUMPOINTS; points++)
{
...
}
, -
,
. -
.
.
(.24.4).
( 49, .)
, .
690 24
. 24.4
NUMPOINTS, RADIUS
SEED, , ,
.
Visual Studio.
, , SerialPI,
for,
. -
.
Program.cs,
. ParallelPI.
, SerialPI
try .
try return
Parallel.For, :
try
{
Parallel.For (0, NUMPOINTS, (x) =>
{
int xCoord = random.Next(RADIUS);
int yCoord = random.Next(RADIUS);
double distanceFromOrigin = Math.Sqrt(xCoord * xCoord + yCoord * yCoord);
pointsList.Add(distanceFromOrigin);
doAdditionalProcessing();
});
}
,
for SerialPI. for -
. ,
, .
691
, .
try Parallel.For , -
. ,
SerialPI:
try
{
Parallel.For (...
{
...
});
Main, Program.cs,
ParallelPI Console.WriteLine,
.
.
, -
, .24.5 ( , -
, ,
).
. 24.5
, SerialPI, , ,
ParallelPI - .
,
692 24
SerialPI, , -
, . , pointsList
ParallelPI , SerialPI.
pointsList -
, . (
) , , .
Visual Studio.
?
,
pointsList. - List<double>,
-
. Parallel.For,
, Add, ,
, -
. , ,
, , Add
. -
-
System.Collections.Concurrent,
. ,
- ConcurrentBag<T>.
,
Program.cs,
. using:
using System.Collections.Concurrent;
ParallelPI. , -
List<double>, ,
, ConcurrentBag<double>:
static double ParallelPI()
{
ConcurrentBag<double> pointsList = new ConcurrentBag<double>();
Random random = ...;
...
}
693
, -
, .
,
ConcurrentBag<T> Add,
, -
List<T>.
. -
SerialPI ParallelPI. , ,
.24.6.
. 24.6
pointsList ParallelPI
, , , -
, , , -
SerialPI.
, , ParallelPI, -
, , .
,
ConcurrentBag<T> -
,
. ,
, .
Visual Studio.
pointsList ,
, .
Parallel.For Next Random, , -
- List<T>, -
. , Random
, -
Next .
,
.
694 24
Program.cs,
. ParallelPI. --
Parallel.For random.Next -
lock. ,
, pointsList:
static double ParallelPI()
{
...
Parallel.For(0, NUMPOINTS, (x) =>
{
int xCoord;
int yCoord;
lock(pointsList)
{
xCoord = random.Next(RADIUS);
yCoord = random.Next(RADIUS);
}
double distanceFromOrigin = Math.Sqrt(xCoord * xCoord + yCoord * yCoord);
pointsList.Add(distanceFromOrigin);
doAdditionalProcessing();
});
...
}
, xCoord yCoord
lock. , lock -
, ,
lock, , -
.
.
, SerialPI ParallelPI, .
, ParallelPI
(.24.7).
Visual Studio.
. 24.7
695
, async
await , -
,
, await ,
.
AsParallel,
LINQ-. -
PLINQ , ,
.
Parallel LINQ (PLINQ) ,
Visual Studio.
, -
, .
, ,
.
,
Visual Studio 2015 25
Windows.
Visual Studio 2015, -
.
, .
- async -
, Task ( void).
await,
, -
, :
private async Task<int> calculateValueAsync(...)
{
// calculateValue Task
Task<int> generateResultTask =
Task.Run(() => calculateValue(...));
await generateResultTask;
return generateResultTask.Result;
}
696 24
LINQ- AsParallel -
, :
var over100 = from n in numbers.AsParallel()
where ...
select n;
PLINQ-
PLINQ- WithCancellation ParallelQuery
, :
CancellationToken tok = ...;
...
var orderInfoQuery = from c in
CustomersInMemory.Customers.AsParallel().
WithCancellation(tok)
join o in OrdersInMemory.Orders.AsParallel()
on
-
lock, :
object myLockObject = new object();
...
- lock (myLockObject)
- {
// ,
//
...
}
-
ManualResetEventSlim.
-
,
CountdownEvent. -
-
Barrier
- SemaphoreSlim.
. -
Wait.
, Release,
:
SemaphoreSlim semaphore = new SemaphoreSlim(3);
...
semaphore.Wait();
//
...
semaphore.Release();
697
- ReaderWriterLockSlim. -
-
, - , EnterReadLock. ,
ExitReadLock. -
EnterWriteLock.
, ExitWriteLock, :
ReaderWriterLockSlim readerWriterLock = new
ReaderWriterLockSlim();
CancellationTokenSource -
. -
Cancel
CancellationTokenSource, :
CancellationTokenSource cancellationTokenSource = new
CancellationTokenSource();
CancellationToken cancellationToken =
cancellationTokenSource.Token;
...
// ,
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(3);
...
//
// OperationCanceledException,
// Cancel
// cancellationTokenSource
semaphore.Wait(cancellationToken);
25
Windows
, :
Windows;
-
Windows,
- ;
-
Windows.
Windows
,
-
. -
. Windows Runtime (WinRT),
. Visual Studio
WinRT-, -
, -
. Windows 8
Visual Studio 2013,
Windows Store .
, ,
Windows Phone 8,
699
UWP
. UWP , -
, Xbox- ..
API- , .
, . , -
, ,
, -
.
, -
UWP, Visual
Studio 2015 , .
, Visual
Studio 2015 UWP-,
, Windows 10.
, -
- ,
.
700 25
UWP-
, . -
,
Windows 10. -
UWP-
Windows (UWP) - -
Microsoft https://msdn.microsoft.com/library/dn894631.aspx.
Windows
-
. UWP-
(user experience (UX)). Windows 10 -
,
.
,
, , -
, .
, (GUI)
,
-
, .
Visual Studio 2015
Windows , -
, Microsoft.
,
. ,
, ,
. -
, . ,
, , Windows
10, -
, .
, ,
(
) -
.
Windows 701
UWP
.
UWP- ,
, ,
.
. , -
,
. UWP-
, -
. ,
,
UWP-, ,
, -
.
UWP- , ,
.
, , , -
,
, ,
.
, -
. Windows
, ,
, .
,
. ,
, -
.
UWP-
Guidelines for app suspend and resume -
Microsoft https://msdn.microsoft.com/library/windows/apps/hh465088.
aspx.
UWP-
, Visual Studio 2015, -
Windows Store. ,
.
. -
702 25
,
, Microsoft.
Windows Store,
, ,
, UWP-
. , -
,
, . , UWP-
( ,
). -
, ,
, -
Package.appxmanifest.
Microsoft
.
Package.appxmanifest XML-, -
Visual Studio .
.25.1. -
, , .
. 25.1
703
, :
, ,
;
, -
;
GPS,
;
-
.
,
,
,
, -
.
, UWP-
,
- Microsoft http://msdn.microsoft.com/library/windows/apps/hh464936.
aspx.
, UWP-.
Windows
UWP-, -
Windows, Visual Studio 2015,
Windows 10.
, ,
,
.
-
,
Adventure Works. -
.
Adventure Works.
704 25
</Grid>
</Page>
XAML- <Page>
</Page>. , ,
.
<Page> -
xmlns:id="". XAML,
C# using ,
. ,
, XAML, -
.
, :
xmlns:local="using:Customers"
705
C# Customers.
XAML ,
local. Customers
.
MainPage.xaml,
MainPage.xaml.cs, .
, C#,
.
( using,
, ):
// " " .
// http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace Customers
{
/// <summary>
/// ,
/// .
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
Customers.
MainPage, Page.
Page XAML-
UWP-, MainPage ,
, .
MainPage.xaml. XAML-
, <Page> :
x:Class="Customers.MainPage"
XAML-, ,
MainPage, , .
UWP-. ,
. , .
-
, ( ,
706 25
). -, -
, ,
,
,
. , Visual Studio 2015
-,
- , ,
. -
,
.
UWP- -
, -
-, ,
.
.
Customers
,
(.25.2) ,
- ,
, ( )
, (
, ). ,
, -
.
5-
. 0" Desktop (1280x720)
100% . ,
- . XAML- -
MainPage. Grid:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
Background
Grid . ,
.
707
. 25.2
, Grid.
Page , , -
, , Grid
Button ().
,
:
<Page
...
<Button Content="Click Me"/>
</Page>
,
, ,
. -
,
TextBox, (.25.3).
Grid ,
.
708 25
. 25.3
,
.
. , StackPanel
.
Grid -
, .
TextBlock,
<TextBlock /> XAML
<Grid>:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock />
</Grid>
,
, . ,
XAML
.
TextBlock .
TextBlock , -
, .25.1.
709
25.1
HorizontalAlignment Left
Margin 400,90,0,0
TextWrapping Wrap
VerticalAlignment Top
FontSize 50
,
XAML-, ,
XAML:
<TextBlock HorizontalAlignment="Left" Margin="400,90,0,0" TextWrapping="Wrap"
Text="Adventure Works Customers" VerticalAlignment="Top" FontSize="50"/>
(.25.4).
. 25.4
,
,
, -
, .
710 25
TextBlock 400 ( ) 90 ( -
).
Grid , TextBlock -
, ,
TextBlock Grid.
, , -
HorizontalAlignment VerticalAlignment. ,
, Margin. -
HorizontalAlignment TextBlock
Left, VerticalAlignment Top,
. Margin
, , ,
( )
.
, Margin
0.
TextBlock.
, ,
.
.25.2.
25.2
Margin 330,190,0,0
TextWrapping Wrap
Text ID
VerticalAlignment Top
FontSize 20
Margin 460,190,0,0
TextWrapping Wrap
Text Title
VerticalAlignment Top
FontSize 20
711
25.2 ()
Margin 620,190,0,0
TextWrapping Wrap
VerticalAlignment Top
FontSize 20
Margin 975,190,0,0
TextWrapping Wrap
VerticalAlignment Top
FontSize 20
,
, -
XAML XAML-,
TextBlock </Grid>:
<TextBlock HorizontalAlignment="Left" Margin="330,190,0,0" TextWrapping="Wrap"
Text="ID" VerticalAlignment="Top" FontSize="20"/>
<TextBlock HorizontalAlignment="Left" Margin="460,190,0,0" TextWrapping="Wrap"
Text="Title" VerticalAlignment="Top" FontSize="20"/>
<TextBlock HorizontalAlignment="Left" Margin="620,190,0,0" TextWrapping="Wrap"
Text="First Name" VerticalAlignment="Top" FontSize="20"/>
<TextBlock HorizontalAlignment="Left" Margin="975,190,0,0" TextWrapping="Wrap"
Text="Last Name" VerticalAlignment="Top" FontSize="20"/>
TextBlock
TextBox, , -
.
.25.3. , Text -
(""). ,
id TextBox . ,
(ID) ,
.
712 25
25.3
XAML-
:
<TextBox x:Name="id" HorizontalAlignment="Left" Margin="300,240,0,0"
TextWrapping="Wrap" Text="" VerticalAlignment="Top" FontSize="20"
IsReadOnly="True"/>
<TextBox x:Name="firstName" HorizontalAlignment="Left" Margin="550,240,0,0"
TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="300" FontSize="20"/>
<TextBox x:Name="lastName" HorizontalAlignment="Left" Margin="875,240,0,0"
TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="300" FontSize="20"/>
713
Name ,
, C# -
. , Name x:.
XML http://schemas.microsoft.com/winfx/2006/
xaml, XAML-.
Name .
, Name -
, ,
x:Name Directive http://msdn.microsoft.com/library/
ms752290.aspx.
Width ,
TextWrapping , ,
, .
TextBox
( ).
, NoWrap, ,
.
ComboBox, -
Title TextBlock id
firstName TextBox.
(.25.4).
25.4
x:Name Title
HorizontalAlignment Left
Margin 420,240,0,0
VerticalAlignment Top
Width 100
FontSize 20
XAML- -
:
<ComboBox x:Name="title" HorizontalAlignment="Left" Margin="420,240,0,0"
VerticalAlignment="Top" Width="100" FontSize="20"/>
ComboBox -
, .
714 25
ComboBox.
. -
, Items.
"Object". ComboBoxItem,
. , -
, , Content
Mr (.25.5).
. 25.5
OK. .
XAML- title ComboBox, -
:
<ComboBox x:Name="title" HorizontalAlignment="Left" Margin="420,240,0,0"
VerticalAlignment="Top" Width="100" FontSize="20"/>
<ComboBoxItem Content="Mr"/>
</ComboBox>
. , -
ComboBox <ComboBox>
715
</ComboBox>. ,
Visual Studio ComboBoxItem Content,
Mr.
.
title ComboBox Mrs, Ms Miss.
, XAML-
.
:
<ComboBox x:Name="title" HorizontalAlignment="Left" Margin="420,240,0,0"
VerticalAlignment="Top" Width="75" FontSize="20">
<ComboBoxItem Content="Mr"/>
<ComboBoxItem Content="Mrs"/>
<ComboBoxItem Content="Ms"/>
<ComboBoxItem Content="Miss"/>
</ComboBox>
ComboBox -
, ComboBoxItem, -
, , ,
. ComboBoxItem,
, XAML- ,
-
Object. . -
, -
,
.
TextBox
TextBlock. TextBox -
,
TextBlock .
.25.5.
25.5
XAML- :
<TextBlock HorizontalAlignment="Left" Margin="300,390,0,0" TextWrapping="Wrap"
Text="Email" VerticalAlignment="Top" FontSize="20"/>
<TextBox x:Name="email" HorizontalAlignment="Left" Margin="450,390,0,0"
TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="400" FontSize="20"/>
<TextBlock HorizontalAlignment="Left" Margin="300,540,0,0" TextWrapping="Wrap"
Text="Phone" VerticalAlignment="Top" FontSize="20"/>
<TextBox x:Name="phone" HorizontalAlignment="Left" Margin="450,540,0,0"
TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="200" FontSize="20"/>
(.25.6).
717
. 25.6
,
.
,
.25.7.
. 25.7
718 25
, , .
.
,
, Last Name .
, -
,
Visual Studio.
.
, Customer, .
. TextBlock
,
.
Visual Studio
.
. 25.8
719
WINDOWS
, Visual Studio 2015, -
UWP-
, .
,
,
, .
Visual
Studio (Debug Target). -
-
,
, ,
. , -
,
(
).
.25.9.
. 25.9
Visual Studio
,
. , -
, ,
.
,
. -
90 , 90
. .25.10 Customers, -
. .
.
720 25
/
90 90
. 25.10
, ,
, 1366
768, 10,6 .
,
-
1366 768.
.25.11
90 ,
.
, , -
. .25.12 Customers,
(2560
1440, 27- ). ,
.
721
. 25.11
, , -
Windows 10 (, ,
). , Windows
(, ),
.
722 25
. 25.12
, Visual Studio
.
, -
, .
, -
.
, ,
, ,
. ,
,
.
- 12" Tablet ,
, , -
,
,
(.25.8). ( -
- 0" Desktop.)
,
- . ,
723
Grid
,
.
Grid
-
Grid. Grid , ,
. -
Grid ,
:
,
- , ,
.
, -
,
.
. ,
.
Customers, , -
: ,
, , .
(.25.13), -
.
,
- . 10 -
, .
-
.
.25.14,
, .
, ,
. , , TextBox-
Email Phone
. ,
724 25
,
. ,
.
.
. 25.13
. 25.14
725
-
Customers,
.
-
Grid- XAML- Customers
Grid. ,
, Grid- 10
Grid- 20
:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Margin="10,20,10,20">
</Grid>
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap"
Text="Adventure Works Customers" ... />
...
</Grid>
Grid-,
UWP-
,
.
Grid- <Grid.RowDefinitions>-,
:
<Grid Margin="10,20,10,20">
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
</Grid>
<Grid.RowDefinitions> .
.
*, ,
Windows
-
. , ,
, ,
Customers.
726 25
Grid TextBlock,
Adventure Works Customers,
</Grid.RowDefinitions>.
TextBlock Grid.Row
0.
TextBlock
Grid. ( Grid -
.)
Grid.Row .
, -
, .
TextBlock Row ( ), -
Row TextBlock -
TextBlock . Grid -
, ,
TextBlock. ,
..
Margin HorizontalAlignment
VerticalAlignment Center. TextBlock
.
XAML- Grid TextBlock
( TextBlock ):
<Grid Margin="10,20,10,20">
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Center" TextWrapping="Wrap"
Text="Adventure Works Customers" VerticalAlignment="Center" FontSize="50"/>
...
</Grid>
TextBlock
Grid. Grid-
Grid- ( ,
10*), , ,
Grid.Row 2:
<Grid Margin="10,20,10,20">
<Grid.RowDefinitions>
727
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Center" .../>
<Grid Grid.Row="2">
</Grid>
...
</Grid>
Grid <Grid.RowDefinitions>
<Grid.ColumnDefinitions>:
<Grid Grid.Row="2">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="4*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
, ,
. ,
, 20 .
TextBlock, ID, Title,
Last Name First Name,
Grid </Grid.ColumnDefinitions>.
Grid.Row TextBlock -
0 ( ).
Grid.Column ID 1, Grid.Column
Title 3, Grid.Column First Name 5
Grid.Column Last Name 7.
728 25
Margin TextBlock -
HorizontalAlignment VerticalAlignment Center.
XAML-
( ):
<Grid Grid.Row="2">
<Grid.RowDefinitions>
...
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
...
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="ID" VerticalAlignment="Center" FontSize="20"/>
TextBlock Grid.Row="0" Grid.Column="3" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="Title" VerticalAlignment="Center" FontSize="20"/>
<TextBlock Grid.Row="0" Grid.Column="5" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="First Name" VerticalAlignment="Center" FontSize="20"/>
<TextBlock Grid.Row="0" Grid.Column="7" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="Last Name" VerticalAlignment="Center" FontSize="20"/>
</Grid>
TextBox id , firstName
lastName, ComboBox title, -
Grid
TextBlock Last Name.
1 Grid.
id 1, title
3, firstName 5,
lastName 7.
Margin -
VerticalAlignment Center. Width
HorizontalAlignment Stretch.
,
.
XAML-
:
<Grid Grid.Row="2">
<Grid.RowDefinitions>
...
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
...
</Grid.ColumnDefinitions>
...
<TextBlock Grid.Row="0" Grid.Column="7" ... Text="Last Name" .../>
729
TextBlock Email -
TextBox email Grid,
ComboBox
title. 3 Grid.
Email 1, TextBox
email 3. , Grid.ColumnSpan -
TextBox email 5, ,
, ,
Width .
HorizontalAlignment
Email Center, HorizontalAlignment TextBox
email Left
,
, .
VerticalAlignment Email -
TextBox email Center.
Margin.
XAML-
:
<Grid Grid.Row="2">
<Grid.RowDefinitions>
...
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
...
</Grid.ColumnDefinitions>
...
<ComboBox Grid.Row="1" Grid.Column="3" x:Name="title" ...>
...
730 25
</ComboBox>
<TextBlock Grid.Row="3" Grid.Column="1" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="Email" VerticalAlignment="Center" FontSize="20"/>
<TextBox Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="5" x:Name="email"
HorizontalAlignment="Left" TextWrapping="Wrap" Text=""
VerticalAlignment="Center" Width="400" FontSize="20"/>
</Grid>
TextBlock Phone -
TextBox phone Grid
TextBox email.
5 Grid. -
Phone 1,
TextBox phone 3. Grid.ColumnSpan
TextBox phone 3.
HorizontalAlignment
Phone Center, HorizontalAlignment TextBox
phone Left.
VerticalAlignment -
Center Margin.
XAML-
:
<Grid Grid.Row="2">
<Grid.RowDefinitions>
...
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
...
</Grid.ColumnDefinitions>
...
<TextBox ... x:Name="email" .../>
<TextBlock Grid.Row="5" Grid.Column="1" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="Phone" VerticalAlignment="Center" FontSize="20"/>
<TextBox Grid.Row="5" Grid.Column="3" Grid.ColumnSpan="3" x:Name="phone"
HorizontalAlignment="Left" TextWrapping="Wrap" Text=""
VerticalAlignment="Center" Width="200" FontSize="20"/>
</Grid>
Visual Studio
. -
, ,
-.
. ,
Customers . ,
. ,
731
1366 768. , , -
( ,
90 ). -
.
90 ,
.
Customers -
, -
(.25.15).
. 25.15
732 25
90 ,
, -
25601400.
, -
, , 27 ,
.
1024768.
, -
,
(.25.16).
. 25.16
-
1366768.
,
, ,
, .
. .
733
, Phone
,
(.25.17).
. 25.17
( Windows),
. ,
Visual Studio.
Visual Studio
.
Customers
-, -
- ,
, , -
. ,
,
734 25
. , ,
Customers (.25.18).
. 25.18
.
MainPage.xaml,
. XAML-
(MainPage.xaml.cs), -
. , XAML- -
DeviceFamily-Mobile (
), XAML-
735
MainPage.xaml,
. ,
. XAML-
MainPage.xaml.cs.
Windows
, .
,
. UWP-
,
.
, XAML-, -
.
.
.
,
(
XAML-, -
), ( ,
).
-
. ,
.
XAML Customers
Grid x:Name Visibility, :
Grid -
. Grid
XAML- , .
Visibility , (Visible)
(Collapsed). Visible,
,
, Grid .
736 25
+ , XAML-
XAML, ,
, .
Grid .
-
.
Grid customersColumnarView
:
, ,
, ,
.
TextBlock, -
.
Grid- Customers. FontSize
30:
1 Grid- customersColumnarView
TextBlock, Customers,
Grid. Grid- -
,
,
:
<TextBlock Grid.Row="0" ... />
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
</Grid>
,
, .
Grid-
XAML- TextBlock
ID, Title, First Name Last Name Grid- customersTabularView.
ID 0,
Title 1, First Name 2
Last Name 3.
0:
<Grid.RowDefinitions>
...
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="ID" VerticalAlignment="Center" FontSize="20"/>
<TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="Title" VerticalAlignment="Center" FontSize="20"/>
<TextBlock Grid.Row="2" Grid.Column="0" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="First Name" VerticalAlignment="Center"
FontSize="20"/>
<TextBlock Grid.Row="3" Grid.Column="0" HorizontalAlignment="Center"
TextWrapping="Wrap" Text="Last Name" VerticalAlignment="Center"
FontSize="20"/>
TextBox Grid-
XAML- ComboBox TextBox
738 25
-
(.25.19).
. 25.19
Customers. ,
.
, -
. ,
,
.
,
? , ,
, -
,
,
740 25
. UWP-
. , -
,
.
26.
-
.
- (, ) -
, ,
. ,
, XAML- .
.
XAML Customers
</Grid>, Grid- customersColumnarView, -
:
<Grid x:Name="customersColumnarView" Margin="10,20,10,20" Visibility="Visible">
...
</Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="TabularLayout">
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
.
, ,
.
, .
(trigger), -
:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="TabularLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="660"/>
</VisualState.StateTriggers>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
741
,
660. Customers
.
XAML- ,
:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="TabularLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="660"/>
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="customersTabularView.Visibility"
Value="Visible"/>
<Setter Target="customersColumnarView.Visibility"
Value="Collapsed"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
, .
-
Setter. Setter , -
.
Setter : Grid- customersTabularView
, Grid- customersColumnarView (-
).
TabularLayout
, ,
:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="TabularLayout">
...
</VisualState>
<VisualState x:Name="ColumnarLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="0"/>
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="customersTabularView.Visibility"
Value="Collapsed"/>
<Setter Target="customersColumnarView.Visibility"
Value="Visible"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
742 25
, 660-
. ColumnarLayout: Grid-
customersTabularView , Grid- customersColumnarView
.
.
Customers. -
.
1366 768,
.
1366 768.
Customer
. 660, -
.
Customers, 660
( ). Customers
.
Visual Studio .
,
,
.
UWP- ,
, , , ,
. -
,
,
. ,
,
. ,
- !
UWP-,
.
, ,
.
743
, ,
XAML- . -
Customers,
Customers.
Customers
Customers,
.
Customers -
. AppStyles.xaml,
.
AppStyles.xaml.
XAML-, , -
. AppStyles.xaml :
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Customers">
</ResourceDictionary>
,
. , , ,
, ImageBrush (),
Grid, Customers.
Customers,
, .
Images. Images,
.
Customers
\Microsoft Press\VCSBS\Chapter 25\Resources folder ,
wood.jpg, .
wood.jpg Images Customers.
, ,
Customers.
AppStyles.xaml
XAML-, :
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
744 25
xmlns:local="using:Customers">
<ImageBrush x:Key="WoodBrush" ImageSource="Images/wood.jpg"/>
</ResourceDictionary>
ImageBrush WoodBrush,
wood.jpg.
, , wood.jpg.
AppStyles.xaml ImageBrush , -
:
<ResourceDictionary
...>
<ImageBrush x:Key="WoodBrush" ImageSource="Images/wood.jpg"/>
<Style x:Key="GridStyle" TargetType="Grid">
<Setter Property="Background" Value="{StaticResource WoodBrush}"/>
</Style>
</ResourceDictionary>
, . Style
(, ),
, -
. Grid.
Setter.
Background
WoodBrush, ImageBrush.
.
, (, Red,
), ,
- . -
StaticResource,
.
,
,
App.xaml, AppStyles.xaml.
App.xaml, .
App.xaml :
<Application
x:Class="Customers.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Customers"
RequestedTheme="Light">
</Application>
745
App.xaml ,
, -
.
App.xaml , :
<Application
x:Class="Customers.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Customers"
RequestedTheme="Light">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="AppStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
,
, , AppStyles.xaml.
.
MainPage.xaml
, Customers. XAML
Grid:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
XAML- Background
Style,
GridStyle:
<Grid Style="{StaticResource GridStyle}">
Grid
(.25.20).
, ,
, -
- . -
, 30- , Windows
. ,
Background
-
.
746 25
. 25.20
AppStyles.xaml
GridStyle FontStyle:
TextBlock Segoe
Print. , , .
FontStyle
TextBlock, , -
FontFamily . -
,
, .
AppStyles.xaml HeaderStyle:
747
<Style x:Key="FontStyle"
TargetType="TextBlock">
...
</Style>
<Style x:Key="HeaderStyle" TargetType="TextBlock" BasedOn="{StaticResource
FontStyle}">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Foreground" Value="SteelBlue"/>
</Style>
,
TextBlock HorizontalAlignment , TextWrapping , VerticalAlignment
Foreground. , BasedOn HeaderStyle -
FontStyle. BasedOn
.
, -
customersTabularView
customersColumnarView. (-
),
, HeaderStyle.
AppStyles.xaml :
<Style x:Key="HeaderStyle" TargetType="TextBlock" BasedOn="{StaticResource
FontStyle}">
...
</Style>
<Style x:Key="TabularHeaderStyle" TargetType="TextBlock"
BasedOn="{StaticResource HeaderStyle}">
<Setter Property="FontSize" Value="40"/>
</Style>
,
, Grid
. , Segoe Print ,
.
MainPage.xaml XAML- -
TextBlock Adventure Works Customers Grid-
customersTabularView:
,
TabularHeaderStyle, :
, , ,
, (.25.21).
. 25.21
,
ColumnarHeaderStyle, :
<TextBlock Grid.Row="0" Style="{StaticResource ColumnarHeaderStyle}"
Text="Customers"/>
,
Grid- customersColumnarView .
.
AppStyles.xaml. HeaderStyle,
Setter, -
:
<Style x:Key="HeaderStyle" TargetType="TextBlock" BasedOn="{StaticResource
FontStyle}">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Foreground" Value="SteelBlue"/>
<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
<Setter Property="RenderTransform">
<Setter.Value>
<CompositeTransform Rotation="-5"/>
</Setter.Value>
</Setter>
</Style>
749
,
, 5.
. -
RenderTransform, -
, . ,
x y,
.
, RenderTransform
( Rotation, 5). -
<Setter.Value>.
MainPage.xaml.
(.25.22).
. 25.22
AppStyles.xaml :
<Style x:Key="LabelStyle" TargetType="TextBlock" BasedOn="{StaticResource
FontStyle}">
<Setter Property="FontSize" Value="30"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Foreground" Value="AntiqueWhite"/>
</Style>
TextBlock,
TextBox ComboBox, -
.
, , ,
.
MainPage.xaml . XAML -
TextBlock Grid -
customersTabularView customersColumnarView.
750 25
: Segoe
Print, , 30 (.25.23).
,
.
751
. 25.23
1366768, .
Customers, -
, Visual Studio. ,
TextBox
, .
Segoe Print
,
. , l
1, O -
0.
TextBox , .
, , ,
, Grid-
customersColumnarView. (.25.24).
Visual Studio .
, .25.25 -
Customers, ,
Windows Phone 10.
752 25
. 25.24
,
. ,
, , -
. , Customers
, -
, FontStyle.
, , ,
,
XAML- ,
, ,
. , -
, Microsoft Blend
753
. 25.25
,
Grid, -
- .
,
754 25
. , ,
.
, -
, ,
.
.
,
Visual Studio 2015 26.
Visual Studio 2015, -
.
, .
UWP- UWP-,
Visual Studio 2015,
- Grid.
, Grid-
-
- Grid-
- ,
,
- . , -
, -
.
,
<Style>, , -
, :
<Style x:Key="GridStyle" TargetType="Grid">
<Setter Property="Background"
Value="{StaticResource WoodBrush}"/>
</Style>
Style
, :
<Grid Style="{StaticResource GridStyle}">
26
Windows
, :
, Model View ViewModel ( -
)
Windows;
;
(ViewModel), -
.
25 -
Windows -
,
-, ,
, . -
, , ,
.
, ,
Windows 10,
.
, UWP-
. . ,
,
-
(ViewModel),
- .
756 26 Wndows 10
Model-View-ViewModel
, , -
,
, -, -
.
, , -
-
.
. ,
-
,
-
, ,
C#, - .
,
UWP-, -
.
,
Model View ViewModel (MVVM).
(Model) , ,
(View) .
(ViewModel) ,
,
, - ,
. (.26.1) -
MVVM. ,
. , UWP- -
, ,
.
-
.
, ,
UWP- . , -
, ,
-.
Model-View-ViewModel 757
-
,
-
-
-
. 26.1
-
Customers,
-
. ,
:
,
. , :
, -
, ,
.
.
Customers 25.
Customers
Visual Studio 2015 Customers,
\Microsoft Press\VCSBS\Chapter 26\Data Binding .
Customers, 25, -
, .
Customers,
, . ,
758 26 Wndows 10
Customers .
Customer.cs, .
Rectangle (), ,
TextBlock TextBox, . -
LinearGradientBrush,
- .
XAML- Rectangle, Grid-
customersTabularView, (XAML-
Grid- customersColumnarView Grid
Rectangle, , ):
<Rectangle Grid.Row="0" Grid.RowSpan="6" Grid.Column="1"
Grid.ColumnSpan="7" ...>
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF0E3895"/>
<GradientStop Color="#FF141415" Offset="0.929"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
Customer -
, Customer-,
.
Customer.cs, Customer
,
:
public class Customer
{
public int _customerID;
public int CustomerID
{
get { return this._customerID; }
set { this._customerID = value; }
}
, -
, ,
. ,
.
Customers MainPage.
xaml, -
. XAML-
TextBox id. XAML-,
Text , ,
:
<TextBox Grid.Row="1" Grid.Column="1" x:Name="id" ...
Text="{Binding CustomerID}" .../>
ComboBox ,
ComboBox.)
<Grid x:Name="customersTabularView" ...>
...
<TextBox Grid.Row="1" Grid.Column="1" x:Name="id" ...
Text="{Binding CustomerID}" .../>
...
<TextBox Grid.Row="1" Grid.Column="5" x:Name="firstName" ...
Text="{Binding FirstName}" .../>
<TextBox Grid.Row="1" Grid.Column="7" x:Name="lastName" ...
Text="{Binding LastName}" .../>
...
<TextBox Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="3"
x:Name="email" ... Text="{Binding EmailAddress}" .../>
...
<TextBox Grid.Row="5" Grid.Column="3" Grid.ColumnSpan="3"
x:Name="phone" ... Text="{Binding Phone}" .../>
</Grid>
<Grid x:Name="customersColumnarView" Margin="10,20,10,20"
Visibility="Collapsed">
...
<TextBox Grid.Row="0" Grid.Column="1" x:Name="cId" ...
Text="{Binding CustomerID}" .../>
...
<TextBox Grid.Row="2" Grid.Column="1" x:Name="cFirstName" ...
Text="{Binding FirstName}" .../>
<TextBox Grid.Row="3" Grid.Column="1" x:Name="cLastName" ...
Text="{Binding LastName}" .../>
...
<TextBox Grid.Row="4" Grid.Column="1" x:Name="cEmail" ...
Text="{Binding EmailAddress}" .../>
...
<TextBox Grid.Row="5" Grid.Column="1" x:Name="cPhone" ...
Text="{Binding Phone}" .../>
</Grid>
, -
. ,
{Binding CustomerID} TextBox
id cId,
.
MainPage.xaml,
MainPage.xaml.cs MainPage.
xaml. MainPage ,
.
public MainPage()
{
this.InitializeComponent();
Model-View-ViewModel 761
Customer ,
. , Customer,
, :
Customer customer = new Customer
{
...
};
this.DataContext = customer;
, -
MainPage. XAML- Text="{Binding Path}"
. ,
TextBox id,
TextBox cId Text="{Binding
CustomerID}", , , -
CustomerID Customer, .
-
DataContext, -
.
, -
DataContext, .
,
. , , -
.26.2, John Sharp.
,
. , ,
.26.3.
, ,
, ,
.
(Email) john@
treyresearch.com. ,
762 26 Wndows 10
. 26.2
. ,
, , .
Visual Studio .
Visual Studio Customer
set EmailAddress.
-
.
,
F5, .
Customers, -
, -
, john@treyresearch.com.
,
.
,
set EmailAddress: TextBox
email ,
Customer.
Model-View-ViewModel 763
. 26.3
Visual Studio .
set EmailAd
dress Customer.
, -
, ,
. -
, , ,
764 26 Wndows 10
.
:
, .
XAML-
Mode, Binding. -
, , - .
.
MainPage.xaml , -
, XAML-
TextBox:
<Grid x:Name="customersTabularView" ...>
...
<TextBox Grid.Row="1" Grid.Column="1" x:Name="id" ...
Text="{Binding CustomerID, Mode=TwoWay}" .../>
...
<TextBox Grid.Row="1" Grid.Column="5" x:Name="firstName" ...
Text="{Binding FirstName, Mode=TwoWay}" .../>
<TextBox Grid.Row="1" Grid.Column="7" x:Name="lastName" ...
Text="{Binding LastName, Mode=TwoWay}" .../>
...
<TextBox Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="3"
x:Name="email" ... Text="{Binding EmailAddress, Mode=TwoWay}" .../>
...
<TextBox Grid.Row="5" Grid.Column="3" Grid.ColumnSpan="3"
x:Name="phone" ... Text="{Binding Phone, Mode=TwoWay}" ..."/>
</Grid>
<Grid x:Name="customersColumnarView" Margin="10,20,10,20" ...>
...
<TextBox Grid.Row="0" Grid.Column="1" x:Name="cId" ...
Text="{Binding CustomerID, Mode=TwoWay}" .../>
...
<TextBox Grid.Row="2" Grid.Column="1" x:Name="cFirstName" ...
Text="{Binding FirstName, Mode=TwoWay}" .../>
<TextBox Grid.Row="3" Grid.Column="1" x:Name="cLastName" ...
Text="{Binding LastName, Mode=TwoWay}" .../>
...
<TextBox Grid.Row="4" Grid.Column="1" x:Name="cEmail" ...
Text="{Binding EmailAddress, Mode=TwoWay}" .../>
...
<TextBox Grid.Row="5" Grid.Column="1" x:Name="cPhone" ...
Text="{Binding Phone, Mode=TwoWay}" .../>
</Grid>
Mode Binding ,
, ( )
Model-View-ViewModel 765
. Mode TwoWay
, , ,
.
, -
. ,
,
john@treyresearch.com, , -
,
.
, ,
TwoWay, ,
, john@contoso.com.
Visual Studio .
, - ! ,
, ,
. ( Customer
set EmailAddress ,
,
TextBox.) , -
.
-
PropertyChanged.
INotifyPropertyChanged, , -
,
. .
INotifyPropertyChanged
Customer
Visual Studio Customer.cs.
using:
using System.ComponentModel;
INotifyPropertyChanged.
Customer,
INotifyPropertyChanged (
):
class Customer : INotifyPropertyChanged
766 26 Wndows 10
,
INotifyPropertyChanged. , ,
,
.
Customer PropertyChanged OnProperty
Changed, :
OnPropertyChanged PropertyChanged .
PropertyChangedEventArgs PropertyChanged -
.
OnPropertyChanged.
Customer set -
, OnPropertyChanged, -
(
):
class Customer : INotifyPropertyChanged
{
public int _customerID;
public int CustomerID
Model-View-ViewModel 767
{
get { return this._customerID; }
set
{
this._customerID = value;
this.OnPropertyChanged(nameof(CustomerID));
}
}
NAMEOF
nameof, Customer, ,
, , C#.
, , . -
nameof
, :
public int CustomerID
{
get { return this._customerID; }
set
{
this._customerID = value;
this.OnPropertyChanged("CustomerID");
}
}
,
, , -
. , -
,
. , -
, ,
, , -
.
nameof ,
nameof, -
, .
,
.
Customers, john@
treyresearch.com, 222-2222.
,
, ,
.
Model-View-ViewModel 769
James, , -
, ,
.
Visual Studio .
ComboBox
TextBox
TextBlock .
ComboBox . ,
ComboBox :
,
, .
ComboBox, , -
, . Customers
ComboBox title,
SelectedValue:
, -
XAML-:
<ComboBox ... x:Name="title" ... >
<ComboBoxItem Content="Mr"/>
<ComboBoxItem Content="Mrs"/>
<ComboBoxItem Content="Ms"/>
<ComboBoxItem Content="Miss"/>
</ComboBox>
, ,
, , ,
.
. , -
SelectedValue, ,
. title ComboBox -
,
Mr.
,
, , ,
ComboBox
770 26 Wndows 10
. , -
ComboBox
.
ComboBox title
Visual Studio MainPage.xaml.cs.
MainPage , :
public MainPage()
{
this.InitializeComponent();
this.title.ItemsSource = titles;
this.cTitle.ItemsSource = titles;
this.DataContext = customer;
}
, -
, .
ItemsSource
ComboBox title (,
ComboBox ).
, -
ComboBox, , ,
- , ,
.
.
, DataContext MainPage,
.
MainPage.xaml. XAML-
title cTitle, ComboBox (
):
Model-View-ViewModel 771
, ComboBoxItem-
SelectedValue
Title Customer.
,
.
, (
Mr).
ComboBox , Mr, Mrs, Ms Miss.
,
, . ,
.
Visual Studio .
(ViewModel)
,
,
,
. -
. , MVVM
, (
) ,
(ViewModel).
, -
, :
.
772 26 Wndows 10
,
- . -
.
- , .
,
.
Customers ,
Customer-, ,
, -
.
Customers, \Microsoft Press\VCSBS\Chapter
26\ViewModel .
Customers , ,
.
Customers,
, .
Customers
ViewModel.cs, .
(ViewModel), -
Customer. -
, .
, ViewModel.cs,
(public) ViewModel ,
:
public class ViewModel
{
private List<Customer> customers;
public ViewModel()
{
this.customers = new List<Customer>
{
new Customer
{
CustomerID = 1,
Title = "Mr",
FirstName="John",
LastName="Sharp",
EmailAddress="john@contoso.com",
Model-View-ViewModel 773
Phone="111-1111"
},
new Customer
{
CustomerID = 2,
Title = "Mrs",
FirstName="Diana",
LastName="Sharp",
EmailAddress="diana@contoso.com",
Phone="111-1112"
},
new Customer
{
CustomerID = 3,
Title = "Ms",
FirstName="Francesca",
LastName="Sharp",
EmailAddress="frankie@contoso.com",
Phone="111-1113"
}
};
}
}
ViewModel List<Customer>,
. , -
Model, ,
, .
ViewModel currentCustomer,
, -
:
class ViewModel
{
private List<Customer> customers;
private int currentCustomer;
public ViewModel()
{
this.currentCustomer = 0;
this.customers = new List<Customer>
{
...
}
}
}
ViewModel
Customer, .
ViewModel Current, -
:
774 26 Wndows 10
class ViewModel
{
...
public ViewModel()
{
...
}
Current Customer-.
, null.
ViewModel. ,
, ViewModel, -
.
MainPage.xaml.cs.
MainPage , Customer, , -
ViewModel. ,
DataContext MainPage,
ViewModel ( ):
public MainPage()
{
...
this.cTitle.ItemsSource = titles;
MainPage.xaml. XAML
TextBox ComboBox,
, Current, -
( ):
<Grid x:Name="customersTabularView" ...>
...
<TextBox Grid.Row="1" Grid.Column="1" x:Name="id" ...
Text="{Binding Current.CustomerID, Mode=TwoWay}" .../>
<TextBox Grid.Row="1" Grid.Column="5" x:Name="firstName" ...
Model-View-ViewModel 775
, -
. ,
John Sharp ( ).
,
, -
.
Visual Studio .
Current, -
.
,
currentCustomer , Current
, , -
(View) (ViewModel).
, Command.
,
. ,
776 26 Wndows 10
.
, XAML ,
,
.
XAML-,
, , , ,
ICommand.
.
CanExecute. , ,
. ,
. -
, , ,
, ,
, .
Execute. .
CanExecuteChanged. ,
. ,
, , . -
, ,
, -
, CanExecute false.
CanExecuteChanged,
, .
-, -
ICommand.
Command
Visual Studio Customers,
.
Customers .
Command.cs, .
, Command.cs,
using:
using System.Windows.Input;
Model-View-ViewModel 777
ICommand.
Command ,
ICommand, ,
:
public class Command : ICommand
{
}
Command :
public class Command : ICommand
{
private Action methodToExecute = null;
private Func<bool> methodToDetectCanExecute = null;
}
Action Func 20
. Action ,
,
, Func<T> ,
, ,
, T. ,
Command- ,
methodToExecute. methodToDetectCanExecute
, -
( - ,
).
Command , -
: Action- Func<T>-. -
, methodToExecute
methodToDetectCanExecute:
public Command : ICommand
{
...
public Command(Action methodToExecute, Func<bool> methodToDetectCanExecute)
{
this.methodToExecute = methodToExecute;
this.methodToDetectCanExecute = methodToDetectCanExecute;
}
}
.
, .
Execute CanExecute Command, -
, methodToExecute methodToDetectCanExecute:
778 26 Wndows 10
,
methodToDetectCanExecute null, ,
, CanExecute true.
Command CanExecuteChanged:
public Command : ICommand
{
...
public bool CanExecute(object parameter)
{
...
}
, -
, Command-,
,
CanExecute, . -
CanExecuteChanged .
CanExecute, ,
- ,
.
Model-View-ViewModel 779
using:
using Windows.UI.Xaml;
Command ,
:
public class Command : ICommand
{
...
private Func<bool> methodToDetectCanExecute = null;
private DispatcherTimer canExecuteChangedEventTimer = null;
DispatcherTimer ,
Windows.UI.Xaml, , -
.
CanExecuteChanged
canExecuteChangedEventTimer.
Command canExecuteChangedEventTimer_Tick,
:
public class Command : ICommand
{
...
public event EventHandler CanExecuteChanged;
CanExecuteChanged,
. ,
,
. -
, ,
(
) .
780 26 Wndows 10
Command ,
:
public class Command : ICommand
{
...
public Command(Action methodToExecute, Func<bool> methodToDetectCanExecute)
{
this.methodToExecute = methodToExecute;
this.methodToDetectCanExecute = methodToDetectCanExecute;
DispatcherTimer-
.
,
.
Command
ViewModel. , -
.
ViewModel NextCustomer
PreviousCustomer
Visual Studio ViewModel.cs.
using
ViewModel, , INotifyPropertyChanged:
...
using System.ComponentModel;
namespace Customers
{
public class ViewModel : INotifyPropertyChanged
{
...
}
}
,
Current. ViewModel ,
PropertyChanged,
, .
ViewModel
:
public class ViewModel : INotifyPropertyChanged
{
...
public ViewModel()
{
...
}
-
ViewModel . IsAtStart true ,
currentCustomer ViewModel ,
IsAtEnd true,
.
, ,
IsAtStart IsAtEnd:
public ViewModel()
{
this.currentCustomer = 0;
this.IsAtStart = true;
this.IsAtEnd = false;
Count ,
, 0 Count 1.
currentCustomer
( ) . ,
IsAtStart IsAtEnd -
, , Current
PropertyChanged . ,
ViewModel.
, ,
.
ViewModel NextCustomer
PreviousCustomer, :
public class ViewModel : INotifyPropertyChanged
{
private List<Customer> customers;
private int currentCustomer;
public Command NextCustomer { get; private set; }
public Command PreviousCustomer { get; private set; }
...
}
Command-, -
.
ViewModel NextCustomer ( -
) PreviousCustomer ( ) Command-:
public ViewModel()
{
this.currentCustomer = 0;
this.IsAtStart = true;
this.IsAtEnd = false;
this.NextCustomer = new Command(this.Next, () =>
{ return this.customers.Count > 1 && !this.IsAtEnd; });
this.PreviousCustomer = new Command(this.Previous, () =>
{ return this.customers.Count > 0 && !this.IsAtStart; });
...
}
Command- NextCustomer
Next , , Execute.
- () => { return this.customers.Count >1 && !this.IsAtEnd; }
, CanExecute.
true ,
, ViewModel
. Command- PreviousCustomer
: Previous
784 26 Wndows 10
, CanExecute
() => { return this.customers.Count > 0 && !this.IsAtStart; }, -
true , ,
ViewModel .
,
.
, ViewModel NextCustomer PreviousCustomer,
.
, .
Microsoft publishes, -
UWP-, ,
, , .
UWP- : ,
, , . -
,
.
.
Microsoft
http://msdn.microsoft.com/library/windows/apps/
hh465302.aspx.
XAML- -
.
.
, More (),
Model-View-ViewModel 785
. ,
,
, Label
. -
:
(XAML) - Microsoft
https://msdn.microsoft.com/library/windows/apps/xaml/hh965329.aspx.
CommandBar
(, ICom
mandBarElement). AppBarButton,
AppBarToggleButton AppBarSeparator.
CommandBar.
, ,
,
: The specified value cannot be assigned to the collection.
UWP- (,
Previous Next, ), -
AppBarButton.
.
Symbol Icon
. -
.
Command, ,
ICommand.
ViewModel PreviousCustomer NextCustomer.
, .
.
Customers John Sharp. .26.4
, , -
Next Previous.
, Previous . , IsAtStart
ViewModel- true, CanExecute Command,
Previous, , .
.
. ,
.
Next. 2,
Diana Sharp, ( ) Previous
786 26 Wndows 10
. 26.4
. IsAtStart true, -
CanExecute true. -
,
CanExecuteChanged,
.
, Command -
. , -
CanExecuteChanged
.
Next .
3, Francesca Sharp,
Next .
true IsAtEnd ViewModel,
CanExecute Command Next false
.
787
, , -
, , -
. Next Previous
.
Visual Studio .
. ,
INotifyPropertyChanged , -
.
UWP- Model View ViewModel ,
(ViewModel),
.
-
XAML- , :
<TextBox ... Text="{Binding FirstName}" .../>
- INotifyPropertyChanged
- , -
PropertyChanged
, :
class Customer : INotifyPropertyChanged
{
...
public event PropertyChangedEventHandler
PropertyChanged;
-
, - , :
, <TextBox ... Text="{Binding FirstName, Mode=TwoWay}"
- .../>
,
-, (ViewModel),
, -
ICommand,
Button, Button , -
- :
, <Button x:Name="nextCustomer" ...
Command="{Binding Path=NextCustomer}"/>
27
Windows
, :
Entity Framework
(entity-),
, ;
- Representational State Transfer (REST), -
entity-;
-
REST;
,
- REST.
26
Windows Model View ViewModel
(MVVM). , ViewModel, -
,
,
- .
26 , -
, ViewModel,
.
Windows.
MVVM. , , , UWP-
-
.
790 27
Microsoft Azure
, - RESTful, -
, Windows-, -
Windows.
Windows8.1,
Windows 10 (
, ). -
, .
-
Windows https://azure.
microsoft.com/documentation/articles/app-service-mobile-dotnet-backend-windows-store-
dotnet-get-started-preview/.
, ,
. ,
,
, .
, Microsoft, -
,
. -
,
. -, -
, UWP-,
,
Windows, -
. -, ,
Windows 10,
,
. -
,
-.
- ,
-
,
. -
, ,
, -, -
. -
791
Entity- - -
Windows -
entity- -
. 27.1
Entity Framework , -
.
,
. -
, AdventureWorks,
Adventure Works.
-
Entity Framework,
, .
, Entity
Framework - Microsoft, http://
msdn.microsoft.com/data/aa937723.
,
, , Microsoft Azure
SQL Database, - Azure. -
,
, .
792 27
Azure . Azure, -
, https://
azure.microsoft.com/pricing/free-trial/. , Azure ,
Microsoft,
Azure. Microsoft
https://signup.live.com/.
- , Basic,
.
SQL Database https://azure.
microsoft.com/en-us/pricing/details/sql-database/.
793
. 27.2
. .
.
,
( AdventureWorks).
,
.
, -
.27.3.
IP-
. . ,
,
OK.
, , -
.
794 27
. 27.3
.
, -
. ,
, IP-.
AdventureWorks
SalesLT Customer. ,
, UWP- Customers,
. Entity Framework, -
, , -
(null)
, .
Customer NameStyle, PasswordHash
PasswordSalt, .
-
,
Customer.
795
AdventureWorks
Azure AdventureWorks.
AdventureWorks SQL Database
, Visual Studio.
Visual Studio Visual Studio.
. 27.4
Visual Studio,
.
,
(.27.5).
. 27.5
Visual Studio ,
SQL Server Visual Studio (.27.6).
796 27
. 27.6
SQL Server
AdventureWorks, , SalesLT.Customer,
.
. ,
(-
).
. 27.7
797
NameStyle, Ctrl , , -
PasswordHash PasswordSalt.
PasswordSalt, .
Visual Studio . -
, (.27.7).
.
SQL Server,
Visual Studio 2015.
entity-
AdventureWorks
Entity Framework entity-,
. ,
, ADO.NET,
, -
SQL-. ADO.NET, , ,
SQL, -
, , -
SQL-,
- . Entity Framework
, SQL.
Entity Framework
: entity-,
, -
, .
,
.
C# -
(Language-Integrated Query (LINQ)). Entity-
SQL SELECT, .
, , entity- -
SQL- INSERT, UPDATE DELETE
. ,
Entity Framework
, ,
SQL-.
798 27
entity-
Customer, AdventureWorks. -
entity-, database-first,
.
Entity Framework
. Entity Framework ,
,
, .
,
entity- , Code First
to an Existing Database - Microsoft,
http://msdn.microsoft.com/data/jj200620.
entity- AdventureWorks
Visual Studio Customers, \Microsoft
Press\VCSBS\Chapter 27\Web Service .
Customers 26.
, -
, , First Last,
.
Customers
( Customers), ,
.
.
- ASP.NET. ,
.NET
Framework 4.6 ( ).
AdventureWorksService OK.
ASP.NET AdventureWorksService
ASP.NET 4.6 Web API,
.
-
OK,
ASP.NET.
. 27.8
, -
UWP- ,
Entity Framework. - (
UWP-) entity-.
Web API ,
-, -
. - entity-
UWP- Customers.
800 27
Customers,
.
Customers
. AdventureWorksService -
, Customers ,
OK.
, - AdventureWorksService -
, . -
AdventureWorksService,
.
, .
.
.
- Visual Studio -
(Microsoft Edge),
. AdventureWorksService , -
-, -
,
AdventureWorks.
URL- - http://localhost:
50000/, . -
Microsoft
, OK.
ASP.NET -,
IIS Express, URL- .
50000,
.
, .
Models,
AdventureWorksService, ,
.
AdventureWorksService
.
ADO.NET EDM. AdventureWorksModel,
. EDM.
entity- .
?
EF , .
801
.
, Microsoft
SQL Server, .
, -
.
tcp:<servername>.database.windows.net,1433, <servername> -
Azure SQL,
. SQL Server
, -
.
AdventureWorks, OK (.27.9).
. 27.9
802 27
AdventureWorks, -
.
, -
. . -
, Web.Config :,
AdventureWorksEntities.
(.27.10).
. 27.10
. 27.11
EDM Customer -
Entity Model (.27.12).
. 27.12
804 27
,
, OK.
- , Entity Framework
entity- ,
T4, , NuGet.
Entity Framework Microsoft:
(.27.13).
. 27.13
AdventureWorksModel.edmx -
AdventureWorksModel.Context.tt,
AdventureWorksModel.Context.cs.
AdventureWorksEntities. (
EDM.)
public partial class AdventureWorksEntities : DbContext
{
public AdventureWorksEntities()
: base("name=AdventureWorksEntities")
{
}
AdventureWorksEntities DbContext,
,
. -
,
. web.config,
<ConnectionStrings>. ,
, ,
EDM. ,
, -
.
, .
OnModelCreating AdventureWorksEntities .
Customers .
DbSet<Customer>. - DbSet ,
, ,
. SQL- SELECT,
,
DbContext.
806 27
AdventureWorksEntities ,
password.
,
web.config EDM
:
, .
, Entity Framework,
. Customers
:
807
- REST
entity-, -
. -
, UWP- entity-.
Visual Studio 2015 -
- ASP.NET, entity-,
Entity Framework. - entity-
.
-, .
-, REST-,
-
, HTTP- -
. , , -
URL-,
-. , Adventure Works
, ,
:
http://Adventure-Works.com/DataService/Customers/1
URL- -
1. ,
XML JavaScript Object Notation (JSON). -
REST- JSON- -
:
{
"CustomerID":1,
"Title":"Mr",
"FirstName":"Orlando",
"LastName":"Gee",
"EmailAddress":"orlando0@adventure-works.com",
"Phone":"245-555-0173"
}
808 27
REST- , ,
HTTP- -
. , , ,
HTTP GET- -. HTTP ,
POST, PUT DELETE, ,
. -
HTTP- ,
- REST, .
,
.
entity- REST -
.
.
- AdventureWorks
Visual Studio, AdventureWorksService
Controllers, ,
.
-
Web API2 , Entity Framework,
(.27.14).
. 27.14
809
-
Customer (AdventureWorksService.Models).
AdventureWorksEntities (AdventureWorksService.
Models). . -
, CustomersController,
(.27.15).
. 27.15
// GET: api/Customers
public IQueryable<Customer> GetCustomers()
{
return db.Customers;
}
// GET: api/Customers/5
[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> GetCustomer(int id)
{
Customer customer = await db.Customers.FindAsync(id);
if (customer == null)
{
return NotFound();
}
return OK(customer);
}
// PUT: api/Customers/5
810 27
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutCustomer(int id, Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != customer.CustomerID)
{
return BadRequest();
}
db.Entry(customer).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Customers
[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> PostCustomer(Customer customer)
{
...
}
// DELETE: api/Customers/5
[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> DeleteCustomer(int id)
{
...
}
...
}
GetCustomers
Customers Entity Framework .
Entity Framework
811
Customers.
, HTTP GET-
- URL- api/Customers.
GetCustomer ( GetCustomers) -
. CustomerID
, Entity Framework
. GetCustomer , -
HTTP GET- URL- api/Customers/n,
n , .
PutCustomer , -
HTTP PUT-.
, Entity Framework
. PostCustomer HTTP
POST- .
(
). , DeleteCustomer -
HTTP DELETE-
.
, Web API, -
, . -
, - ,
. -
, -
.
.
, , -
- .
Cloud Service Funda
mentals Data Access LayerTransient Fault Handling http://social.technet.
microsoft.com/wiki/contents/articles/18665.cloud-service-fundamentals-data-access-layer-
transient-fault-handling.aspx.
- REST -
ASP.NET Web API Web API
http://www.asp.net/web-api.
812 27
,
, CustomersController,
-
Entity Framework. ASP.Net Web API
ValuesController.cs ,
.
CustomersController , -
AdventureWorksEntities ,
.
, .
( YourPassword .)
public class CustomersController : ApiController
{
private AdventureWorksEntities db = new
AdventureWorksEntities("YourPassword");
// GET: api/Customers
public IQueryable<Customer> GetCustomers()
{
return db.Customers;
}
...
}
, -
Customers,
-
. Customers -
-.
Controllers ValuesController.cs,
. OK,
.
ValuesController .
HomeController. -
-, -.
AdventureWorksService,
, (Google Chrome).
- , -
(.27.16).
813
. 27.16
API. ,
REST-,
- (.27.17).
. 27.17
http://localhost:50000/api/Customers/1,
.
G e t C u s t o m e r
CustomersController, 1 .
, Web API ,
, api.
814 27
GetCustomer
, JSON-, .
( ModifiedDate -
, ):
{"CustomerID":1,"Title":"Mr","FirstName":"Orlando","LastName":"Gee","EmailAddre
ss": "orlando0@adventure-works.com","Phone":"245-555-0173","rowguid":
"3f5ae95e-b87d-4aed-95b4-c3797afcb74f","ModifiedDate":"2001-08-01T00:00:00"}
- Visual Studio.
, - ,
Azure. -,
Visual Studio 2015 - -
- .
-
AdventureWorksService, . -
- (.27.18).
. 27.18
815
- Microsoft
Azure.
Azure.
, , -
. Visual
Studio Microsoft.
- New.
Create Web App On Microsoft Azure -
.
(
Entity Framework -). -
App Service Plan
Create New App Service Plan .
Resource group
Create New Resource Group .
Create () (.27.19).
- -
,
. 27.19
816 27
Validate connection, , -,
-, , .
,
.
.
- .
, , -
.
- Visual Studio.
-
UWP- Customers -
. .NET Framework HttpClient, -
- -
HTTP REST, HttpResponseMessage,
, -.
HTTP-.
-, ,
-, .
.
JSON-, Json.NET,
Customers.
.
, -
-, ,
.
,
, -
, .
,
(, , 20 ). -
- ,
(ViewModel) Customers
.
.
- AdventureWorks
DataSource.
cs Customers, . -
OK, .
817
, -
Customers. ViewModel,
-, ,
.
Customers,
NuGet.
SQL Server,
. -.
, NuGet: Customers
Filter All, Json.NET.
, , Newtonsoft.Json.
.
OK.
NuGet: Customers.
ViewModel.cs,
.
using:
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
ViewModel , -
, ViewModel. <webappname>
-, ,
-:
public ViewModel()
{
...
}
...
}
818 27
ServerUrl -.
client -.
public ViewModel()
{
...
this.customers = null;
this.client = new HttpClient();
this.client.BaseAddress = new Uri(ServerUrl);
this.client.DefaultRequestHeaders.Accept.
Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
customers , -
, , DataSource.
cs, .
client -,
. REST -
, Customers
JSON. -
client .
Customer.cs,
Customers, .
Customer Phone
, :
...
}
- , Customers
, ,
, .
819
( Customers
.)
ViewModel.
GetDataAsync:
, -
api/customers GetAsync HttpClient.
AdventureWorks .
GetAsync
HttpResponseMessage, Task-. HttpResponseMessage
, , , ,
, -,
ReadAsStringAsync, Content,
HttpResponseMessage.
JSON-, ,
Customer-
customers DeserializeObject, -
JsonConvert, Json.NET.
currentCustomer ViewModel
, IsAtStart IsAtEnd
, ViewModel.
820 27
, GetDataAsync
, . -
UWP- .
-
, -
. AdventureWorks
,
, .
, , get Current:
public Customer Current
{
get
{
if (this.customers != null)
{
return this.customers[currentCustomer];
}
else
{
return null;
}
}
}
GetDataAsync , ,
MainPage
. -
, , -
.
ViewModel ,
, , :
public ViewModel()
{
...
this.NextCustomer = new Command(this.Next,
() => { return this.customers != null &&
this.customers.Count > 1 && !this.IsAtEnd; });
this.PreviousCustomer = new Command(this.Previous,
821
,
.
MainPage.xaml
MainPage.xaml.cs, .
MainPage , -
:
public MainPage()
{
...
ViewModel viewModel = new ViewModel();
viewModel.GetDataAsync();
this.DataContext = viewModel;
}
ViewModel.
,
.
, GetDataAsync, ,
Orlando Gee (.27.20).
, , -
.
Visual Studio .
, ,
, , -
, . UWP-
-
ProgressRing ( ).
,
ViewModel -.
822 27
. 27.20
Customers
ViewModel.cs. ViewModel
GetDataAsync _isBusy IsBusy:
private bool _isBusy;
public bool IsBusy
{
get { return this._isBusy; }
set
{
this._isBusy = value;
this.OnPropertyChanged(nameof(IsBusy));
}
}
GetDataAsync ,
:
823
,
GetData IsBusy true. finally -
IsBusy false
.
MainPage.xaml. XAML-
ProgressRing, ,
Grid :
<Grid Style="{StaticResource GridStyle}">
<ProgressRing HorizontalAlignment="Center"
VerticalAlignment="Center" Foreground="AntiqueWhite"
Height="100" Width="100" IsActive="{Binding IsBusy}"
Canvas.ZIndex="1"/>
<Grid x:Name="customersTabularView" Margin="40,104,0,0" ...>
...
Canvas.ZIndex "1", -
ProgressRing ,
Grid.
-
.
, -
,
. ,
, GetDataAsync ,
, .
,
:
824 27
, -
.
Visual Studio .
,
REST -
,
. ASP.NET Web API , -
HTTP PUT-, POST-
DELETE-. PUT-
-, POST-
, DELETE- . , ASP.
NET Web API ,
.
REST -
REST - PUT- ,
. AdventureWorks Service,
888-888-8888, , ,
. ,
, REST - -
.
-
( -
-,
, ,
, REST - 825
). REST -
,
-.
, ,
CreditAccount, ,
PUT-. -
.
.
, , -
,
.
Data Consistency Primer https://msdn.microsoft.com/
library/dn589800.aspx.
Customers,
,
.
REST- -
AdventureWorksService. -
. ,
, -
Adventure Works,
. , , ,
- .
- ,
,
, - -
.
, -
.
ViewModel
Visual Studio. Customers ViewModel.
cs, . Visual Studio
.
Customers, -
, . ViewModel.
826 27
cs,
\Microsoft Press\VCSBS\Chapter 27 -
, .
ViewModel.cs ,
, . ViewModel
, ,
ViewModel: , . -
Properties For Managing The Edit Mode (
).
IsBrowsing. ,
. ,
FirstCustomer, LastCustomer, PreviousCustomer NextCustomer
.
IsAdding. ,
. FirstCustomer,
LastCustomer , PreviousCustomer NextCustomer .
AddCustomer, SaveChanges DiscardChanges,
.
IsEditing. ,
. , -
FirstCustomer, LastCustomer, PreviousCustomer NextCustomer.
EditCustomer, -
. , SaveChanges DiscardChanges,
AddCustomer .
EditCustomer .
IsAddingOrEditing. , -
.
, .
CanBrowse. true, -
-.
, FirstCustomer, LastCustomer,
PreviousCustomer NextCustomer,
,
, :
public ViewModel()
{
...
this.NextCustomer = new Command(this.Next,
() => { return this.CanBrowse &&
this.customers != null && !this.IsAtEnd; });
this.PreviousCustomer = new Command(this.Previous,
() => { return this.CanBrowse &&
, REST - 827
CanSaveOrDiscardChanges. true,
-.
Methods For Fetching And Updating Data ( -
) .
GetDataAsync. , .
-
.
ValidateCustomer. Customer-
FirstName LastName, , .
EmailAddress Phone, , -
, . true,
, false .
, SaveChanges.
, EmailAddress Phone, -
-
Regex, System.Text.RegularExpressions.
, Regex-
, , ,
IsMatch, Regex-, ,
. Regex -
- Microsoft
http://msdn.microsoft.com/library/30wbz966.
CopyCustomer.
Customer-.
EditCustomer -
. ,
, .
Customers
ViewModel.cs, .
ServerUrl ViewModel
:
private const string ServerUrl = "http://<webappname>.azurewebsites.net/";
828 27
<webappname> -,
.
ViewModel.cs Methods For Fetching And Updating Data, -
, . ValidateCustomer
Add:
// ()
private void Add()
{
Customer newCustomer = new Customer { CustomerID = 0 };
this.customers.Insert(currentCustomer, newCustomer);
this.IsAdding = true;
this.OnPropertyChanged(nameof(Current));
}
Customer-. CustomerID,
0,
. , -
.
( -
),
, PropertyChanged, ,
Current- .
ViewModel
Command, :
ViewModel AddCustomer,
:
public ViewModel()
{
...
this.LastCustomer = new Command(this.Last, ...);
this.AddCustomer = new Command(this.Add,
() => { return this.CanBrowse; });
...
}
Add. -
, -
, REST - 829
( AddCustomer ,
).
Add Methods For Fetching And Updating Data
Customer oldCustomer
Edit:
//
//
//
private Customer oldCustomer;
private void Edit ()
{
this.oldCustomer = new Customer();
this.CopyCustomer(this.Current, this.oldCustomer);
this.IsEditing = true;
}
Current- oldCustomer
.
.
,
oldCustomer.
ViewModel
Command, :
ViewModel EditCustomer, -
:
public ViewModel()
{
...
this.AddCustomer = new Command(this.Add, ...);
this.EditCustomer = new Command(this.Edit,
() => { return this.CanBrowse; });
...
}
AddCustomer,
, Edit.
Methods For Fetching And Updating Data
ViewModel Edit Discard:
830 27
// , ,
//
private void Discard ()
{
// ,
if (this.IsAdding)
{
this.customers.Remove(this.Current);
this.OnPropertyChanged(nameof(Current));
}
// ,
//
if (this.IsEditing)
{
this.CopyCustomer(this.oldCustomer, this.Current);
}
this.IsBrowsing = true;
}
, -
, , -
.
, (
, Add )
PropertyChanged, ,
. -
, , -
oldCustomer, , ,
.
.
DiscardChanges Command
ViewModel (-
):
public class ViewModel : INotifyPropertyChanged
{
...
public Command EditCustomer { get; private set; }
public Command DiscardChanges { get; private set; }
...
public ViewModel()
{
...
this.EditCustomer = new Command(this.Edit, ...);
this.DiscardChanges = new Command(this.Discard,
() => { return this.CanSaveOrDiscardChanges; });
}
...
}
, REST - 831
, DiscardChanges ,
CanSaveOrDiscardChanges true,
- -
.
Methods For Fetching And Updating Data Discard
SaveAsync, .
async:
// ,
// -,
private async void SaveAsync()
{
//
if (this.ValidateCustomer(this.Current))
{
// ,
this.IsBusy = true;
try
{
// HTTP-
// JSON
var serializedData = JsonConvert.SerializeObject(this.Current);
StringContent content =
new StringContent(serializedData, Encoding.UTF8, "text/json");
// ,
// - HTTP POST-
if (this.IsAdding)
{
var response =
await client.PostAsync("api/customers", content);
if (response.IsSuccessStatusCode)
{
// TODO:
}
// TODO: POST-
}
//
// , PUT-
else
{
string path = $"api/customers/{this.Current.CustomerID}";
{
// TODO:
}
finally
{
this.IsBusy = false;
}
}
}
.
.
, IsBusy ViewModel
true, ,
, -. (-
, IsActive
ProgressRing, Customers, -
, .)
try , -
, ,
. , -
PostAsync HttpClient, -
POST-. , POST-
PostCustomer CustomersController -,
Customer. -
JSON.
, -
PutAsync HttpClient.
PUT-, PutCustomer CustomersController
-. PutCustomer
.
- JSON-.
, IsBusy false,
ProgressRing .
SaveAsync // TODO:
, :
if (response.IsSuccessStatusCode)
{
// ID
Uri customerUri = response.Headers.Location;
var newCust = await this.client.GetAsync(customerUri);
if (newCust.IsSuccessStatusCode)
{
var customerData = await newCust.Content.ReadAsStringAsync();
, REST - 833
this.CopyCustomer(
JsonConvert.DeserializeObject<Customer>(customerData), this.Current);
this.OnPropertyChanged(nameof(Current));
this.IsAdding = false;
this.IsBrowsing = true;
}
else
{
// TODO: GET-
}
}
CustomerID Customer ,
AdventureWorks, .
, -
, ,
. -
. , -
POST- GET-, -
. , HttpResponseMessage-
- POST- URL-,
. URL-
Headers.Location, api/
Customers/n, n .
GET- URL-, GetAsync
HttpClient.
ReadAsStringAsync. -
, .
,
-, ,
Headers.Location ,
POST-. , -
, , -
, , ,
, .
SaveChanges Command
ViewModel
:
public class ViewModel : INotifyPropertyChanged
{
...
public Command DiscardChanges { get; private set; }
public Command SaveChanges { get; private set; }
...
public ViewModel()
834 27
{
...
this.DiscardChanges = new Command(this.Discard, ...);
this.SaveChanges = new Command(this.SaveAsync,
() => { return this.CanSaveOrDiscardChanges; });
...
}
...
}
, -
.
- -
. ,
ModifiedDate
, . ,
, rowguid -
Customer GUID. (
Customer, ,
Adventure Works,
.)
GUID . GUID -
, Windows,
( , Windows
GUID, , ).
GUID-
, , Customer,
AdventureWorks.
-
AdventureWorksService Controllers
CustomersController.cs, .
PostCustomer ,
, , :
// POST api/Customers
[ResponseType(typeof(Customer))]
public async Task<IHttpActionResult> PostCustomer(Customer customer)
{
if (!ModelState.IsValid)
{
...
}
customer.ModifiedDate = DateTime.Now;
, REST - 835
customer.rowguid = Guid.NewGuid();
db.Customers.Add(customer);
await db.SaveChangesAsync();
...
}
PutCustomer ModifiedDate,
, ,
, , :
// PUT api/Customers/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutCustomer(int id, Customer customer)
{
...
customer.ModifiedDate = DateTime.Now;
db.Entry(customer).State = EntityState.Modified;
...
}
- , ,
- , -
-, , .
, ,
, .
- , , -
, ViewModel
. -
ViewModel.
.
ViewModel
Customers ViewModel.cs.
, , Properties For "Busy"
And Error Message Handling (
).
IsBusy _lastError
LastError:
836 27
// TODO: , -
:
catch (Exception e)
{
this.LastError = e.Message;
}
else, -
, // TODO: GET- ,
:
else
{
this.LastError = response.ReasonPhrase;
}
ReasonPhrase HttpResponseMessage , -
, -.
if, else,
, :
if
{
...
this.IsAtEnd = (this.customers.Count == 0);
this.LastError = String.Empty;
}
else
{
this.LastError = response.ReasonPhrase;
}
LastError .
, REST - 837
ValidateCustomer
return , :
ValidateCustomer validationErrors -
Customer,
.
LastError.
SaveAsync. , ,
HTTP -:
private async void SaveAsync()
{
//
if (this.ValidateCustomer(this.Current))
{
...
try
{
...
// ,
// - HTTP POST-
if (this.IsAdding)
{
...
if (response.IsSuccessStatusCode)
{
...
if (newCust.IsSuccessStatusCode)
{
...
this.IsBrowsing = true;
this.LastError = String.Empty;
}
else
{
// TODO: GET-
this.LastError = response.ReasonPhrase;
}
}
// TODO: POST-
else
{
this.LastError = response.ReasonPhrase;
}
}
//
838 27
// , PUT-
else
{
...
if (response.IsSuccessStatusCode)
{
this.IsEditing = false;
this.IsBrowsing = true;
this.LastError = String.Empty;
}
// TODO: PUT-
else
{
this.LastError = response.ReasonPhrase;
}
}
}
catch (Exception e)
{
// TODO:
this.LastError = e.Message;
}
finally
{
this.IsBusy = false;
}
}
}
Discard, , -
:
private void Discard()
{
...
this.LastError = String.Empty;
}
, -
.
.
, Customers,
, .
Customers
MainPage.xaml. XAML-
MainPage , Grid
TextBlock:
, REST - 839
<Page
x:Class="Customers.MainPage"
...>
ErrorMessageStyle,
TextBlock, AppStyles.xaml.
Text TextBlock -
LastError ViewModel:
...
<TextBlock Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="7"
Style="{StaticResource ErrorMessageStyle}" Text="{Binding LastError}"/>
...
<TextBlock Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2"
Style="{StaticResource ErrorMessageStyle}" Text="{Binding LastError}"/>
TextBox ComboBox,
,
, -
,
.
IsEnabled IsAddingOrEditing ViewModel:
...
<TextBox Grid.Row="1" Grid.Column="1" x:Name="id"
IsEnabled="{Binding IsAddingOrEditing}" .../>
<TextBox Grid.Row="1" Grid.Column="5" x:Name="firstName"
IsEnabled="{Binding IsAddingOrEditing}" .../>
<TextBox Grid.Row="1" Grid.Column="7" x:Name="lastName"
IsEnabled="{Binding IsAddingOrEditing}" .../>
840 27
,
<Page.BottomAppBar>
. -
AddCustomer,
EditCustomer, SaveChanges -
DiscardChanges:
<Page ...>
...
<Page.TopAppBar >
...
</Page.TopAppBar>
<Page.BottomAppBar>
<CommandBar>
<AppBarButton x:Name="addCustomer" Icon="Add"
Label="New Customer" Command="{Binding Path=AddCustomer}"/>
<AppBarButton x:Name="editCustomer" Icon="Edit"
Label="Edit Customer" Command="{Binding Path=EditCustomer}"/>
<AppBarButton x:Name="saveChanges" Icon="Save"
Label="Save Changes" Command="{Binding Path=SaveChanges}"/>
<AppBarButton x:Name="discardChanges" Icon="Undo"
Label="Undo Changes" Command="{Binding Path=DiscardChanges}"/>
</CommandBar>
</Page.BottomAppBar>
</Page>
, , ,
, .
, REST - 841
Customers
,
. Customers, ,
TextBox ComboBox , -
.
.
, , First, Next, Previous Last
( , First Previous ,
-
). Add Edit,
Save Discard , AddCustomer EditCustomer -
, ,
SaveChanges DiscardChanges ,
(.27.21).
. 27.21
842 27
.
, -
. ,
Add Edit,
Save Discard. ,
(.27.22).
. 27.22
: , Test
, Test 2 , -
Save.
, -
ValidateCustomer. LastError
ViewModel , -
TextBlock, LastError
(.27.23).
, REST - 843
. 27.23
Discard ,
. ,
.
Add. ( ID, -
0). .
, name@
organization.com ( -
, ).
Save. ( -
), . ID
, ,
.
, -
. ,
844 27
, ,
.
, Visual Studio .
, Entity Framework
entity-, -
SQL Server. .
, REST -, UWP-
,
, entity-, , ,
-, ( ViewModel).
. ,
C#
Visual Studio 2015 ,
Windows10. .
, , C#, -
,
C#.
C#
Visual Studio 2015,
. , C# .
2001 , , C#
, ,
Microsoft .NET Framework 1.0. ,
Visual Studio .NET Framework 1.1 2003- 2005-,
C# 2.0 .NET Framework2.0. C# 3.0
, , --
, , LINQ-. C# 4.0
, ,
, ,
. C# 5.0 -
async
await. C# 6.0 ,
, ,
nameof, .
C#
-
Windows. ,
845
, Windows 8 ,
, Windows,
,
, , -
Windows10. , Visual Studio 2015 C#
.
C# Visual Studio? !
entity- , -
ADO.NET EDM.
Entity Framework EDM, ,
, , -
, .
,
( ,
)
REST - ASP.NET,
, - Web API.
Web API2 ,
Entity Framework.
entity- entity- entity-, -
, entity-
REST - ASP.NET
- UWP- -
HttpClient.
BaseAddress HttpClient -
, :
string ServerUrl = "http://localhost:50000/";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ServerUrl);
GetAsync HttpClient -
REST - URI , .
UWP- GetAsync , , -
GetAsync,
ReadAsStringAsync HttpResponseMessage, -
:
846 27
- PostAsync HttpClient
REST
- UWP- URI , . -
HttpResponseMessage,
PostAsync, , POST-
, :
HttpClient client = ...;
StringContent newCustomer = ...;
var response = await client.PostAsync(
"api/customers", newCustomer);
if (!response.IsSuccessStatusCode)
{
// POST-
}
- PutAsync HttpClient
REST -
- UWP- URL .
HttpResponseMessage, PutAsync,
, PUT- , -
:
HttpClient client = ...;
StringContent updatedCustomer = ...;
string path =
$"api/customers/{updatedCustomer.CustomerID}";
var response = await client.PutAsync(
path, updatedCustomer);
if (!response.IsSuccessStatusCode)
{
// PUT-
}
Microsoft Visual C#.
8-
.
.
.
. , . , .
.
.
, 192102, -, . (. ), 3, , . 7.
034-2014, 58.11.12.000
, .
19.10.16. 70100/16. . . . . 68,370. 1000. 0000.
. .
142300, , . , . , 1.
: www.chpk.ru. E-mail: marketing@chpk.ru
: 8(496) 726-54-10, : (495) 988-63-87