C#
21. .NET
32. C#
42.1.
52.2. #
62.3. C#
72.4. C#
83. C#
93.1.
103.2.
113.3.
123.4.
133.5.
143.6.
153.7.
163.8. -
174. C#
184.1.
194.2. .
204.3. .
214.4. .
224.5. .
235.
245.1. .
255.2. .
265.3. .
275.4. .
285.5. .
295.6. .
305.7. .
31 .NET
32
33 , - Microsoft
34 . NGWS,
35 Next Generation Web Services Next Generation Windows Services.
36 - -. "-" (web
37service) .
38
39 C#, ASP ADO
40ASP+ ADO+. Preview ,
41 - . , ,
42 COM+ Windows DNA. NGWS ,
43 .
44
45 .NET ( ""). ASP+ ASP.NET, ADO+
46 ADO.NET.
47
48 .NET , XML , ,
49 , ASP . , ,
50 .
52 .NET
53 .NET Java , ,
54 . Java JSP, ASP. Java
55 , , .
56
57 Windows DLL Hell, <windows.h>, MFC, VB, Delphi, VBScript
58 -.
59 - .
60
61 . Windows API - .
62Visual Basic RAD (rapid application development) .
63 .
64 COM+ Windows DNA. ++ - ,
65 . Delphi , Microsoft.
66J++ .
67
68 .
69 , .
70, - ,
71 .
72 , .
73 , Microsoft .
74, C# - Delphi.
76 .NET
77 , Windows, 78?
79
80.NET (CLR, common language runtime).
81Java Runtime Environment, . ,
82 (managed code) , .NET runtime.
83 Windows (
84 dotSITE).
85 .NET.
86 , ,
87CLR. Microsoft Intermediate Language (MSIL, IL). ,
88 , . , -,
89 , .
90 .
91 (Base Class Library), -
92 . , , .NET,
93 .
94MSIL BCL , .NET Preview .
95C#, Visual Basic.NET, Managed C++, JScript, .NET (CLS compliant)
96. J#, Pascal .NET, COBOL.NET, Perl.NET , Mixal.NET
97
98
99 - .
100 .
101 ,
102 (versioning).
103 .NET
104 , ,
105 .
106 - Windows , ,
107, .
108
109 , (ADO.NET), (ASP.NET),
110windows (Windows Froms), XML (DOM, XSD, XSLT, /, ADO.NET),
111 (System.Net), (remoting), COM+ (Enterprise Services,
112Serviced components), (System.Security.Cryptography).
113
114.NET . XML .
115 -.
116
117 .NET
118 ASP.NET, . ASP.NET ,
119, ( ASP).
120
121 . C
122 J2ME, , .
124
125 , ,
126 DLL, COM, ASP, ADO, Visual Basic, MFC.
127 - ,
128 .
129 .
130
131 , .NET.
132
133 , Windows Interop
134( DLL Windows API), COM Interop ( .NET
135 COM vice versa), COM+, ASP
136ASP.NET .
137
138 ++
139 . ,
140 . ,
141 ++ ,
142 , , Visual Basic. ,
143 ,
144 /++.
145 .
146
147 Web.
148 , ,
149Visual Basic C++,
150 ,
151 Web .
152 , Microsoft - C#.
153 - , , , "
154", .
155 , COM+ Web . C#,
156 : C++, C, Java,
157SmallTalk, Delphi, Visual Basic .. , C#
158 , ( ),
159 (, ,
160), .
161, , ++,
162 .
163Web
164 - , C#
165 -
166 , . , C#
167 Web -
168 Web ,
169Internet .
170 C# Web ,
171 : XML (Extensible Markup Language) SOAP (Simple Object Access Protocol).
172 Web Web
173, C# ,
174Web - .
175
176 - ,
177 , . 178 Assembler Java.
179 ,
180. Java - , , ,
181,
182, , - (
183 - JIT ). C++ -
184 ,
185 ,
186
187 , " ",
188 ,
189 . " ",
190 . C#,
191 ,
192 . , " ",
193 ,
194 ,
195 . C#
196 .
197 , , .
198 C#
199 (vesioning). , C++ Java, ,
200 .
201 . native
202 .
203 .
204 C# , .
205 , , , ,
206 . (namespaces),
207 -.
208 ,
209 , . C# using
210 , . ,
211 System , Console.
212 , using
213 .
214 ++ C# . ,
215, ++, "->", "::", "."? ,
216 . ,
217 ,
218 . C#, "->" ( unsafe ,
219 ), "::" .
220 "." .
221 . C/++
222, . C# - Unicode
223 char ( wchar_t, ++) 64- - long ( __int64).
224 C# .
259
260
C#
261C#, ,
262 ,
263 .NET. .NET
264 ( , .NET) -
265. , ,
266 .NET, .
267 C# C++ Java. ,
268 , C# .
269 - , ,
270, .NET - .
271 .
272, C# Java.
273 , -
274 , .
275 , ,
276 .
277 - ( Java C#
278 , , C++).
279 Java ( ,
280 ). .
281 , , ""
282 XML.
283 , XML284 .
285 C# , - , ,
286 . , ,
287 ,
288.
C#
289
290 C#. ,
291 . :
292 C#, "Hello, world":
using System;
class Hello{
static void Main() {
Console.WriteLine("hello, world");
}
}
293 hello.cs
294
csc hello.cs
295 .
296 . , csc.exe - C
297Sharp Compiler
298 hello.exe, , "hello, world".
299 Main - . (, C++
300Java) , . .
301 WriteLine System.Console.
302 .
303 - dll-,
304. /target:library
305 ,
306 . - ,
307, , , .
308 .
309, C# ,
310. CSC:
311
/out:<file>
( -
)
/target:exe
( )
( : /t:exe)
/target:winexe
Windows ( :
/t:winexe)
/target:library
DLL ( : /t:library)
/target:module
,
( : /t:module)
312* : (DLL), ,
313 . - DLL. -
314 (assembly).
315 ( /addmodule).
/nooutput[+|-]
;
( : /d)
/define:< >
#define mark1
/doc:<file>
XML
316
317
/recurse:<>
, .
/main:<>
, (
) ( : /m)
/reference:< >
(
: /r)
318* : , public,
319 . ,
320 /addmodule.
/addmodule:<
>
321
322
/win32res:<file>
Win32(.res)
/win32icon:<file>
/resource:<resinfo>
.NET ( : /res)
323* : resinfo :
324filename[,identifier[,mimetype]], filename - , identifier -
325( ), mimetype - ( ).
/linkresource:<resinfo>
(
)( : /linkres)
326
327
/debug[+|-]
/debug:{full|pdbonly}
('full' - ,
)
/optimize[+|-]
( : /o)
(
: /incr)
/incremental[+|-]
328
329
/warnaserror[+|-]
/warn:<n>
(0-4) ( : /w)
/nowarn:<
>
330* : - num1[,num2[...]]
331
332
/checked[+|-]
/unsafe[+|-]
unsafe (unsafe - ,
)
333
334
@<file>
/help
( : /?)
/nologo
335
336
/baseaddress:<address>
/bugreport:<file>
/codepage:<n>
/fullpaths
/nostdlib[+|-]
(mscorlib.dll).
.NET Framework.
337
338
C#
339 "" - .
340 C#.
// .NET Framework
using System;
// , SampleProgram
namespace SampleProgram
{
///
/// Client -
///
class Client
{
///
///
///
private string _name;
///
///
///
private int _balance;
///
/// .
///
/// ,
/// .
///
public string Name
{
// ,
//
get
{
return _name;
}
//
// value
set
{
_name = value;
}
}
///
/// .
/// ,
/// .
///
public int Balance
{
get
{
return _balance;
}
}
///
///
///
///
///
///
- ,
.
name
initialCash ,
//
if (Transaction.CheckID(transactionID))
//
_balance += amount;
else
//
throw new Exception("Wrong transaction ID");
}
///
/// ToString,
/// System.Object. .
///
///
public override string ToString()
{
return Name + " (" + Balance + ")";
}
}
///
/// .
///
public class Transaction
{
///
/// ,
///
///
/// true, false
public static bool CheckID( int id )
{
// ,
2
return id % 2 != 0;
}
}
///
/// - ,
.
///
///
public class Application
{
///
///
///
public static void Main()
{
// Johny Smith
finally
{
Console.WriteLine(" : " + client);
}
}
}
}
341 C#. ,
342 Client . , 343. :
344
345
346
347
348 C#
349 C#, ,
350 .
351 , , ,
352, int. -
353 . , , (,
354 , decimal) .
355 , . ,
356 , . ,
357 . :
public struct Point
{
public int x, y;
public Point(int p1, int p2)
{
x = p1;
y = p2;
}
}
358 .
359 () .
360 . ,
361 .
362, , :
public enum Season {Winter, Spring, Summer, Fall};
363 C# ,
364 .
365
sbyte
-128..127
byte
0..255
8-
8-
char
short
U+0000..U+FFFF
-32.768..32.767
16- Unicode-
16-
16-
0.65535
-2.147.483.648..2.147.483.647
32-
32-
0..4.294.967.295
-9,223,372,036,854,775,808..9,223,372,036,854,775,807 64-
64-
0..18,446,744,073,709,551,615
ushort
int
uint
long
ulong
368
float
double
+1.5E-45..+3.4E38
+5.0E-324..+1.7E308
7
15-16
369 decimal
370Decimal 128- . ,
371 , .
decimal
1.0E-28 to 7.9E28
28-39
380 54 System.Int32,
381System.ValueType ToString(), .
382 , .
383 object string ( System.Object
384System.String .NET Framework)
385 unsafe .
386
387 C# . C#
388 - , , .
389 C# 7 : , , .
390 , :
391
392
, static.
. :
using System;
namespace StaticVariables
{
///
/// Singleton Singleton ().
///
/// .
///
///
class Singleton
{
///
///
///
private static Singleton _instance;
//
public static Singleton Instance
{
get
{
// ,
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}
///
/// ,
///
///
private Singleton()
{
}
///
/// hello, world!
///
public void HelloWorld()
{
Console.WriteLine("Hello, world");
}
}
public class Application
{
public static void Main()
{
Singleton singleton = Singleton.Instance;
singleton.HelloWorld();
}
}
}
393
394
.
- , .
using System;
namespace InstanceVariables
{
///
///
///
class Man
{
///
/// -
///
private static string _prefix = "Mr.";
///
///
///
public string _name;
///
///
///
///
public Man( string name )
{
_name = name;
}
///
///
///
///
public void ChangePrefix( string prefix )
{
_prefix = prefix;
}
///
///
///
///
public override string ToString()
{
return _prefix + " " + _name;
}
}
public class Application
{
public static void Main()
{
//
Man smith = new Man("Smith");
Man pitt = new Man("Pitt");
//
Console.WriteLine(" : " + smith + ", " + pitt);
//
pitt._name = "Pumpkin";
Console.WriteLine(" : " + smith + ", " +
pitt);
//
pitt.ChangePrefix("Dr.");
Console.WriteLine(" : " + smith + ", " + pitt);
}
}
}
395
:
: Mr. Smith, Mr. Pitt
: Mr. Smith, Mr. Pumpkin
: Dr. Smith, Dr. Pumpkin
396
397
398
, ,
- . ,
.
399
400
,
. :
401
402
403
404
- , .
,
, .
for, while, foreach, if.
using System;
namespace LocalVariables
{
public class Application
{
static int i = 117;
public static void Main()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("i = {0}", i);
}
Console.WriteLine("i = {0}", Application.i);
}
}
}
405
i
i
i
i
i
i
i
i
i
i
i
=
=
=
=
=
=
=
=
=
=
=
0
1
2
3
4
5
6
7
8
9
117
406
407
408 C# C++. C# :
409, (jagged):
410
411
:
. C++:
int[] array = new int[10];
int[] array = {1, 2, 3, 4, 5};
412
. []:
int element = array[0];
413
0 N - 1, N - .
414
415
416
417
418
.
- "" .
, . ,
(Java),
, .
419
. :
. [],
:
420
421
,
0 N - 1, N - .
422
423
424
425
(jagged) - , , . ,
:
426
427
.
int element = array[0][1];
428
429
430
,
. array[1][15],
array[0][15].
431
432 C# - ,
433 .
434 const:
const int a = 2;
435 static, ,
436. ,
437 :
const int a = 3;
const int b = a + 7;
438
439
440 - , .
441 if, for, while goto. C#
442 : switch, do foreach.
443if..else
444 if..else, ,
445 .
446 if (a > b)
447 {
448
449 }
450 else
451 {
452
453 }
serverObject.Initialize();
460
461 :
462 // , 0
463 if (x != 0)
464 {
465
d /= x;
466 }
467 else
468
return;
469
470 // , , , null
471 if (command.Parameters["RETURN_VALUE"].Value != Convert.DBNull)
472
return command.Parameters["RETURN_VALUE"].Value;
473 else
474
return null;
475
476 for
477 for ,
478.
479
480
CreateArray(items); //
481
482
483
484
485
486 : ,
487 : , ,
488 , ,
489 - .
490 for :
491// for (int i = 0; i < 10; i++) sum += array[i];
492 ,
493 (
494 10) .
495while
496 while : ,
497 . while :
498 //
499 int num = 678;
500
501 // - 0
502 int len = 0;
503
504 //
505 while (num > 0)
506 {
507
len++;
508
num /= 10;
509 }
510
511 Console.WriteLine(len);
512
513 : . ,
514 , - .
515 ADO.NET -
516SqlReader:
517 // result set? ,
518 while (reader.Read())
519 {
520
//
521
users.Add(new User((int)reader["ID"]);
522 }
523
524 - .
525 ( ).
526goto
527goto - . :
528 switch ( )
529 .
530. -
531:
532
Exit:
return 0;
533
534 , goto:
535
goto Exit;
536
case 0:
542
543
break;
544
case 1:
545
546
goto case 2;
case 2:
547
548
goto default;
549
default:
550
Console.WriteLine("bye");
551
break;
552 }
553switch
554 switch ,
555 .
556 if, ,
557.
558 switch :
559 int a
= 1;
560
561 switch (a)
562 {
563
564
case 0:
//, a = 0
565
Console.WriteLine("A = 0");
566
break;
567
case 1:
568
//, a = 1
569
Console.WriteLine("A = 1");
570
break;
571
default:
572
//, ,
573
574
break;
575 }
581do
582 do . while,
583 , . .
584 string s = "A, B, C, D";
585
586 do
587 {
588
s = s.Substring(s.IndexOf(",") + 1);
591 , ,
592.
593foreach
594foreach - , C#.
595 , ,
596 IEnumerable.
597 foreach :
598 // DataSet
599 DataSet data = GetData();
600
601 foreach (Row row in data.Tables[0].Rows)
602 {
603
604 }
605
606 .
607
608 C# - ,
609 .
610
611 ,
612 . C# , .NET.
613 ,
614. , System Collections,
615Data , Data SqlClient, OleDbClient, SqlTypes. 616System.Data.SqlClient, System.Data.OleDbClient, System.Data.SqlTypes. ,
617 "" namespace , .
618 , , ,
619 , , .
620 HT Electronics, Web Admin
621 Processor Manager, ,
622 com.HTElectronics.WebAdmin com.HTElectronics.ProcessorManager.
623 com.HTElectronics.Common.
624 -
625 , . R.
626Gamma et al. "Design Patterns. Elements Of Reuseable Object-Oriented Software" J. Larman "Applying
627UML and Design Patterns". .
628, - Main - .
629 , , ,
630 .
631
632 . Java
633 - ,
634 , public- ..
635 C# . .
636 -
637 .
638 , - , Web-.
639
640 . C#
641: , XML642.
643
644 ( ), /* */:
/* */
int count;
645
646 ( ).
647 //:
int count;
//
648XML C#
649
, XML
650C# . C#,
651 "/doc". , C#, XML ,
652 . , ,
653 HTML- . , e
654 . ...
655
<c>
<code>
<example>
<exception>
<list>
<para>
<param>
<paramref>
<permission>
<remarks>
<returns>
<see>
<seealso>
<summary>
<value>
656<c>
657 <c> , , , .
658<code>
659 <code> , <c>,
660.
661<example>
662 <example> -
663 .
664<exception>
665 <exception> .
666 cref="..." System.Exception. ,
667 .
668:
/// <exception cref="System.Exception"> </exception>
class SampleClass : Exception {
}
673<list>
674 <list> , ,
675. type, : "bullet" -
676 , "number" - "table" - .
677 <list> : <listheader> <item>.
678 - <term> <description>.
679<listheader> , <item>
680. , <listheader>
681 <item> <term>, <term> <description>.
682 <term> :
public class SampleClass {
/// <list type="bullet">
/// <listheader>
/// <term> </term>
/// </listheader>
/// <item>
/// <term> </term>
/// <description> </description>
/// </item>
/// <item>
/// <term> </term>
/// <description> </description>
/// </item>
/// <item>
/// <term> </term>
/// <description> </description>
/// </item>
/// </list>
public static void Main () {
}
}
683<para>
684 <para> . ,
685 <return> <remark>.
686<param>
687 <param> . name
688 , .
public class SampleClass {
/// <param name="input"> </param>
public static void SampleMethod (String input) {
}
689<paramref>
690 <paramref> , . name
691 . :
public class SampleClass {
/// <paramref name="input"/> - .
public static void SampleMethod (String input) {
692<permission>
693 <permission> .
694 cref="..." System.Security.PermissionSet.
695 :
using System;
class SampleClass{
/// <exception cref="System.Security.PermissionSet">
</exception>
public static void SampleMethod() {
}
public static void Main() {
}
696 :
<?xml version="1.0"?>
<doc>
<members>
<member name="M:SampleClass.SampleMethod">
<permission cref="T:System.Security.PermissionSet">
</permission>
</member>
</members>
</doc>
697<remarks>
698 <remarks> .
699<returns>
700 <returns> .
701 :
using System;
class SampleClass{
/// <returns> </returns>
public static double PiSample() { return 3.1415926; }
public static void Main() {
}
702<see>
703 <see> , ,
704 . cref="..." - . :
using System;
class SampleClass{
/// <para> Main System.Console. <see cref="System.Console"/> for console
operations. </para>
public static void Main() {
System.Console.WriteLine("SampleClass Console Output");
}
705<seealso>
706 <seealso> , " ".
707 cref="..." - .
708<summary>
709 <summary> .
710 <remarks>. :
using System;
/// <remarks> </remarks>
class SampleClass{
/// <summary> Main SampleClass </summary>
public static void Main() {
}
711<value>
712 <value> property.
713
714
715
, xml "///". ,
716 , . ,
717 , .
718
, , .
719 , xml , xml
720 . ,
721 .
722 html xml- .
723 ( C#), html , xml-,
724 C#, xsl .
xml
725
726
xml , .
727-, ,
728 . , using System String,
729 xml System.String. T:System.String. xml,
730 , , .
731:
N
: , , , ,
(field)
Property
( - ,
..)
; .
732
733 , ,
734, . .
735 .
736 C#,
737.
738 .NET Console.
739 : ,
740 . -, , .
741 / ( , ,
742, ), .
743 4 : Read, ReadLine, Write WriteLine.
744 , - .
745 Read
746 Read . int,
747 , -1, . :
do
{
int i = Console.Read();
if (i != -1)
Console.WriteLine("{0} ({1})", (char)i, i);
else
break;
} while (true);
748 .
749 ReadLine
750 ReadLine (
751 ). string null,
752.
do
{
string s = Console.ReadLine();
if (s != null)
Console.WriteLine(" : " + s);
else
break;
} while (true);
757 .
758 , , "{n}" n-
759 ( 0):
Console.Write(", {0}", Name);
761
762:
763 . ,
764 C#. -
765, - - .
766 .
767 , - (
768 ), (, , , , ,
769 ) . .
770 :
// public, ,
// internal -
public class HelloWorldClass
{
public void HelloWorld()
{
Console.WriteLine("Hello, world");
}
}
771 :
public abstract class AgentFactory
{
public void WriteInfo()
{
Console.WriteLine("I'm agent factory");
}
public abstract Agent CreateAgent();
}
772 (,
773, ).
774 . , :
public class FootballAgentFactory : AgentFactory
{
public Agent CreateAgent()
{
return new FootballAgent();
}
}
775 , - ,
776sealed:
public sealed class IAmTheCoolest
{
public void WhoAmI()
{
Console.WriteLine("I am cool and I don't want any inheritance");
}
}
//
public class IAmMoreCoolThanTheCoolest : IAmTheCoolest
{
public void IAmTheCoolest()
{
Console.WriteLine("I'm even cooler that the coolest");
}
777 , , .
778 C# ,
779:
public class Base1
{
}
public class Base2
{
}
public interface Interface1
{
}
public interface Interface2
{
}
//
public class MyClass : Base1, Base2
{
}
//
public class MyClass2 : Base1, Interface1, Interface2
{
}
780 ,
781System.Object object.
782 . .
783
784 , .
public class MyClass
{
// ,
// protected - -
// private - .
public int a;
//
public MyClass()
{
a = 3;
}
}
public class Application
{
public static void Main()
{
MyClass myClass = new MyClass();
// a = 5
Console.WriteLine("a = {0}", myClass.a);
myClass.a += 5;
// a = 10
Console.WriteLine("a = {0}", myClass.a);
}
785 readonly - ,
786 .
public class MyClass
{
//
readonly int a = 1;
//
public MyClass()
{
a = 3;
}
public MyMethod()
{
a = 5; //
}
}
787 volatile, ,
788 .
789 static ,
790. , .
public class MyStaticMemberClass
{
public static int a = 10;
public MyMethod()
{
a = 5;
}
}
public class Application
{
public static void Main()
{
// a = 10
Console.WriteLine("a = {0}", MyStaticMemberClass.a);
MyStaticMemberClass.a = 2;
// a = 2
Console.WriteLine("a = {0}", MyStaticMemberClass.a);
}
}
791
792 , .
public class MyHelper
{
private int a, b;
public MyHelper( int a, int b )
{
this.a = a;
this.b = b;
}
public int Max()
{
return a > b ? a : b;
}
}
public class Application
{
public static void Main()
{
MyHelper helper = new Helper(2, 10);
// MAX(2, 10) = 10
Console.WriteLine("MAX(2, 10) = {0}", helper.Max());
}
}
795
796
static - , . . ,
:
797
798
799
800
801
virtual - , (override) .
new override.
new, , override
- - . override
:
class Base
{
public void MyMethodA()
{
Console.WriteLine("Base.MyMethodA");
}
public virtual void MyMethodB()
{
Console.WriteLine("Base.MyMethodB");
}
}
class Child : Base
{
public new void MyMethodA()
{
Console.WriteLine("Child.MyMethodA");
}
public override void MyMethodB()
{
Console.WriteLine("Child.MyMethodB");
}
}
class Class1
{
static void Main(string[] args)
{
Base childClass = (Base)new Child();
// Base.MyMethodA
childClass.MyMethodA();
// ChildClass.MyMethodB
childClass.MyMethodB();
}
}
802 , .
803 :
804
805 .
806 :
807
808
809
810
811
out - , , . ,
,
.
ref - , . , ,
. ref .
812
813. :
param []
814 :
class Application
{
static void SampleMethod( string text, params string[] args )
{
Console.WriteLine(text);
foreach (string s in args)
{
Console.WriteLine(s);
}
}
public static void Main()
{
SampleMethod("Parameters list:", "Param1", "Param2", "Param3");
}
}
815
816 . ,
817 () .
818 .
819 :
{
get get
get set
}
823 .
824
825
826 .
827 ++ Object Pascal.
828, Microsoft, , .
829 (properties) (indexers).
830 ,
831 ( ,
832 ). C Java
833 () GetItem( int index ). , , ,
834 ,
835.
836 C# .
837 , ,
838 .
839 , , :
this [_]
840 - ( ), -
841 , .
842 , static,
843 out ref.
844 , - get , , set
845( ). get
846 , set value,
847 . , , :
public object this [int index]
{
get
{
return GetItem(index);
}
set
{
SetItem(index, value);
}
}
848 , :
using System;
public CustomIndexerClass
{
// ,
private int internalArray = new int[10];
//
public int this [int index]
{
//
get
{
//
if (index < internalArray.GetLowerBound(0) || index >
internalArray.GetUpperBound(0))
return 0;
//
return internalArray[index];
}
set
{
//
if (index >= internalArray.GetLowerBound(0) && index <=
internalArray.GetUpperBound(0))
internalArray[index] = value;
}
}
public class ApplicationClass
{
public static void Main()
{
CustomIndexerClass myIndexer = new CustomIndexerClass();
myIndexer[1] = 10;
myIndexer[5] = 7;
849 , ,
850 . ,
851 , .
852
853
- .
, ,
.
854
855
.
base. ,
:
856
857
858
class BaseClass
{
int _a;
public int A
{
get
{
return _a;
}
}
public BaseClass( int a )
{
_a = a;
}
}
class InheritedClass : BaseClass
{
public InheritedClass() : base(1)
{
}
}
859
860
861
862
863
- . , .
Singleton.
"" ,
. , C#.
public class Singleton
{
private static Singleton _instance;
public static Singleton Instance
{
get
{
return _instance;
}
}
public static Singleton
{
_instance = new Singleton();
}
}
864
865 - , . .NET CLR
866 , .
867 .
868 , , ~ ():
public class A
{
~A
{
Console.WriteLine("I'm being descructed");
}
}
public class Application
{
public static void Main()
{
A a = new A();
a = null;
}
}
870
871 ,
872 . , (
873 , ,
874 ) . ,
875 , .
interface IEnumGenerator
{
string GenerateEnumeration( ArrayList objects );
}
class ColonEnumGenerator : IEnumGenerator
{
public string GenerateEnumeration( ArrayList objects )
{
string result = "";
foreach (object obj in objects)
result += (result == "" ? "" : ", ") + obj.ToString();
return result;
}
}
class CREnumGenerator : IEnumGenerator
{
public string GenerateEnumeration( ArrayList objects )
{
string result = "";
for (int i = objects.Count - 1; i >= 0; i--)
result += (result == "" ? "" : "\n") + objects[i].ToString();
return result;
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add("Matt");
list.Add("Julia");
list.Add("Robert");
IEnumGenerator cgen = new ColonEnumGenerator();
Console.WriteLine(cgen.GenerateEnumeration(list));
cgen = new CREnumGenerator();
Console.WriteLine(cgen.GenerateEnumeration(list));
}
}
876 , .
interface A
{
void MethodA();
}
interface B : A
{
void MethodB();
}
class C : A, B
{
public void MethodA()
{
}
public void MethodB()
{
}
}
877 (, )
878 . ,
879 :
interface IGameObject
{
string GetName();
}
interface IPlayer
{
string GetName();
}
class Smith : IGameObject, IPlayer
{
public IGameObject.GetName()
{
return "Player";
}
public IPlayer.GetName()
{
return "Smith";
}
}
class Application
{
880
881
882 , .
883:
884, - "" .
885 (
886 ).
class A
{
public int a;
public void AddA()
{
a++;
}
}
class B : A
{
public void SubA()
{
a--;
}
}
class Application
{
public static void Main()
{
B b = new B();
A a = (A)b;
a.a = 0;
// A = 0
Console.WriteLine("A = {0}", b.a);
a.AddA();
// A = 1
Console.WriteLine("A = {0}", b.a);
//
// a.SubA();
b.SubA();
// A = 0
Console.WriteLine("A = {0}", b.a);
}
887 - .
888 .
889
890 C#
891 .
892 operator.
893 : +, -, !, ~, ++, --, true, false +, -,
894*, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, <=,
895 : +
896 +=.
897
operator ( x )
898
operator ( x, y )
899 .
900 :
public struct Vector
{
private double x, y;
public Vector( double x, double y )
{
this.x = x;
this.y = y;
}
public static Vector operator + ( Vector a, Vector b )
{
return new Vector(a.x + b.x, a.y + b.y);
}
public override string ToString()
{
return "[" + x + ", " + y + "]";
}
}
public class Application
{
public static void Main()
{
Vector a(1, 2);
Vector b(2, 3);
Vector c = a + b;
Console.WriteLine("{0} + {1} = {2}", a, b, c);
}
}
901 :
902
903
904 , C#. . - .
905 15 , C++.
906 . , ,
907. ? , , , .
908, , , ,
909 , .
910 "", .
911 - () , "" ,
912 . , (
913 ,
914).
915 . : - ,
916 , .
917 .
918 "" .
919 , .. ,
920 .
921 : :
try
{
,
}
[catch [(_ _)]
{
}]
[finally
{
,
}]
922 - try ,
923 catch .
924( ) finally.
925 , . try,
926 Exception, . , try
927 - throw
928 .
929 :
class ReverseFunction
{
public static double Calculate( double f )
{
if (d == 0)
throw new Exception("Function is undefined in 0");
return 1 / d;
}
public static void Main()
{
try
{
930 .
931 catch . ,
932 :
try
{
CalculateSpline();
}
catch (DivisionByZeroException e)
{
Console.WriteLine("Divizion by 0");
}
catch (OverflowException e)
{
Console.WriteLine("Overflow");
}
catch (Exception e) //
{
Console.WriteLine("Exception: {0}", e);
}
933
934 . ,
935 , ,
936 double, float int ,
937, float VeryCoolNumber.
938 C# .
939, , ,
940 .
941 - , ()
942 .
943explicit implicit .
944 ,
945,
946
class Complex
{
public double Real;
public double Imag;
public Vector( double real, double imag )
{
Real = real;
Imag = imag;
}
public static explicit operator Vector( double real )
{
return new Vector(real, 0);
}
public static explicit operator double( Vector vector )
{
return vector.real;
}
public static void Main()
{
Console.WriteLine("{0}", (double)(Vector)(((double)new Vector(3, 2)) + 4));
}
}
947
948
949 .
950
951 .
952 . . Microsoft.NET
953 (attributes).
954 , Microsoft.NET,
955 C#.
956 , , , ..
957 (metadata)
958 reflection.
959 , UML , ClassBrowser'
960.. C#
961 , .
962 C# DllImport ,
963 Dll.
using System.Runtime.InteropServices;
public class AppMain {
[DllImport("user32.dll")]
public static extern int MessageBoxA(int handle,string message,string caption,int
flags);
public static void Main(){
MessageBoxA(0,"Hello World","Native Message Box",0);
}
}
964 .
965 MethodComments,
966 .
967 . .
968 System.Attribute. Microsoft
969 Attribute . ,
970 .
971 Attribute .
972MethodComments.
using System;
[AttributeUsage(AttributeTargets.Method)]
public class MethodCommentsAttribute : System.Attribute {
private string comments;
public string Comments {
get {
return comments;
}
set {
comments = value;
}
}
public MethodCommentsAttribute(string acomments) {
comments = acomments;
}
public override string ToString() {
return comments;
}
}
973 .
974 C# - AttributeUsage.
975 ( ),
976 . ,
977. ToString() .
978, ,
979. reflection.
using System;
using System.Reflection;
public class SampleClass {
[MethodComments("Some method that returns a void")]
public void SomeVoidMethod() {
}
[MethodComments("Some method that returns an int")]
public int SomeIntMethod() {
return 0;
}
}
public class AppMain {
public static void Main() {
Type comments = typeof(MethodCommentsAttribute);
MethodInfo[] methods = typeof(SampleClass).GetMethods();
object[] attributes;
Console.WriteLine("Method Info for SampleClass");
foreach(MethodInfo method in methods) {
Console.WriteLine("Method Name: {0}",method.Name);
if (method.IsDefined(comments)) {
attributes = method.GetCustomAttributes(comments);
foreach(object obj in attributes)
Console.WriteLine("Method comments : {0}",obj);
}
else
{
Console.WriteLine("Method comments are unavailable.");
}
}
}
}
980
981
982 .NET, C#, - 983 C++.
984, . - 985, , .
986 -
987, -
988 .
989 :
[] [] delegate _ ([]);
990
991 - new, .
992 - (Singlecast) (Multicast).
993 - .
994 IL Disassembler (ildasm).
995 , System.Delegate,
996 - System.MulticastDelegate.
997 , - ,
998 - .
999 :
using System;
public delegate int SingleDelegate(int x);
public class SampleDelegateClass {
int sampleMethod(int x) {
//
Console.WriteLine(x);
return 0;
}
public static void Main(String[] args)
{
//
SampleDelegateClass sdc = new SampleDelegateClass();
//
SingleDelegate sDelegate = new SingleDelegate(sdc.sampleMethod);
Console.WriteLine(sDelegate(255));
}
}
1000 -
1001 - void. , void ,
1002 .
1003System.MulticastDelegate.
1004 Combine System.Delegate:
public static Delegate Combine(Delegate[]);
//
public static Delegate Combine(Delegate, Delegate); //
1005 Remove
1006System.Delegate:
1007public static Delegate Remove(Delegate source, Delegate value);
1008 source - , value - .
1009
1010 += -= .
1011 :
using System;
public delegate void sampleDelegate(int x);
public class DelegateClass1 {
public void sampleMethod(int x) {
Console.WriteLine(x-2);
}
}
public class DelegateClass2 {
public void sampleMethod(int x) {
Console.WriteLine(x+2);
}
}
public class UseDelegates{
public static void Main(String[] args)
{
DelegateClass1 dc1 = new DelegateClass1();
1015
1016
1017 .
1018 , ,
1019 .
1020 C# . ,
1021 , .
1022:
using System;
public delegate void SampleDelegate();
public class SampleClass{
public event SampleDelegate SampleEvent;
public void onEvent()
{
if (SampleEvent != null)
SampleEvent();
}
}
public class Loader{
private static void eHandler1()
{
Console.WriteLine(" : ");
}
private static void eHandler2()
{
Console.WriteLine(" : ");
}
static public void Main ()
{
SampleClass sc = new SampleClass();
sc.SampleEvent += new SampleDelegate(eHandler1);
sc.SampleEvent += new SampleDelegate(eHandler2);
sc.onEvent();
}
}
1023 . ,
1024 .
1025 - , .
1026 :
using System;
public delegate void SampleDelegate();
public interface I {
event SampleDelegate SampleEvent;
void onEvent();
}
public class SampleClass: I
{
public event SampleDelegate SampleEvent;
public void onEvent()
{
if (SampleEvent != null)
SampleEvent();
}
}
public class Loader{
private static void eHandler1() {
Console.WriteLine(" : ");
}
private static void eHandler2() {
Console.WriteLine(" : ");
}
static public void Main () {
I i = new SampleClass();
i.SampleEvent += new SampleDelegate(eHandler1);
i.SampleEvent += new SampleDelegate(eHandler2);
i.onEvent();
}
}
1027 .NET ,
1028, .NET ,
1029: , - ,
1030 , ; ,
1031EventArgs. , .NET
1032 - System.EventHandler.
public delegate void EventHandler(object sender,EventArgs e);
1033 :
:
csc /t:winexe /r:System.DLL;System.WinForms.DLL;Microsoft.Win32.Interop.DLL d.cs
using System;
using System.WinForms;
public class SampleForm : Form
{
private Button button1 = new Button();
public static void Main (String[] args)
{
Application.Run(new SampleForm());
}
public SampleForm()
{
this.Text = "Delegates & Events";
button1.Text = "Event";
button1.Click += new System.EventHandler(buttonClicked);
this.Controls.Add(button1);
}
private void buttonClicked(object sender, EventArgs evArgs)
{
MessageBox.Show(" ");
}
}
1034
1035
1036 C# , , , 1037, .
1038 .
1039 .
1040( ) ,
1041. . (
1042 - )
1043#define.
1044 #define :
#define _
1045 .
1046 #undef:
#undef _
1047 ,
1048 . #if..#else|#elif..#endif.
1049:
#if 1
...
#elif 2
...
#elif k
...
#else
...
#endif
1059, . #region..#endregion
1060 , , Visual Studio .
1061 :
#region _
#endregion
1062
1063
1064 C#
1065 .
1066 :
1067
1068
Win32-,
1069 (,
1070 ), .
1071 ,
1072 , .
1073 MSDN -
1074Win32 API ,
1075:
using System;
using System.Runtime.InteropServices;
using System.Text;
class FileRead
{
const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;
int handle;
public FileRead(string filename)
{
//
handle = CreateFile(filename,
GENERIC_READ,
0,
0,
OPEN_EXISTING,
0,
0);
}
// Win32- CreateFile
[DllImport("kernel32", SetLastError=true)]
static extern unsafe int CreateFile(
string filename,
uint desiredAccess,
uint shareMode,
uint attributes,
// really SecurityAttributes pointer
uint creationDisposition,
uint flagsAndAttributes,
uint templateFile);
// Win32- ReadFile
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool ReadFile(int hFile,
void* lpBuffer, int nBytesToRead,
int* nBytesRead, int overlapped);
// Win32- GetLastError
[DllImport("kernel32", SetLastError=true)]
static extern int GetLastError();
// unsafe, .
// unsafe - unsafe
{...}
public unsafe int Read(byte[] buffer, int index, int count)
{
int n = 0;
// fixed ,
1076
1077