📄 cessentials_examples.htm
字号:
<html><head><title>C# Essentials: Examples</title></head><body bgcolor="#FFFFFF"><img src="http://www.oreilly.com/graphics_new/generic_ora_header_xwide.gif" width="610" height="37" alt="O'Reilly and Associates" class="headerimg"><h2>C# Essentials<br />Examples</h2><p><b>[ Back to: <a href="http://www.oreilly.com/catalog/csharpess/">C# Essentials</a> ]</b></p><h3>Introduction</h3><h4><u>A Minimal C# Program</u></h4><p><pre>class Test { static void Main() { System.Console.WriteLine("Welcome to C#!"); }}</pre><p><h3>C# Language Reference</h3><h4><u>Identifiers</u></h4><p><pre>Ko|n@Ko|n</pre><p><h4><u>Types</u></h4><p><b>Example: Building and Using Types</b><p><pre>// Imports types from System namespace, such as Consoleusing System;class Counter { // New types are typically classes or structs // --- Data members --- int value; // field of type int int scaleFactor; // field of type int // Constructor, used to initialize a type instance public Counter(int scaleFactor) { this.scaleFactor = scaleFactor; } // Method public void Inc() { value+=scaleFactor; } // Property public int Count { get {return value; } }}class Test { // Execution begins here static void Main() { // Create an instance of counter type Counter c = new Counter(5); c.Inc(); c.Inc(); Console.WriteLine(c.Count); // prints "10"; // create another instance of counter type Counter d = new Counter(7); d.Inc(); Console.WriteLine(d.Count); // prints "7"; }}</pre><p><b>Implicit and Explicit Conversions</b><p><pre>int x = 123456; // int is a 4-byte integerlong y = x; // implicit conversion to 8-byte integershort z =(short)x // explicit conversion to 2-byte integer</pre><p><b>Predefined Types</b><p><pre>int i = 5;System.Int32 i = 5;</pre><p><b>Integral Types</b><p><pre>int x = 5;ulong y = 0x1234AF; // prefix with 0x for hexadecimalint x = 123456;long y = x; // implicit, no information lostshort z = (short)x; // explicit, truncates x</pre><p><b>Floating Point Types</b><p><pre>float x = 9.81f;double y = 7E-02; // 0.07int strength = 2;int offset = 3;float x = 9.53f * strength - offset;float x = 3.53f;int offset = (int)x;</pre><p><b>Decimal Type</b><p><pre>decimal x = 80603.454327m; // holds exact value</pre><p><b>Char Type</b><p><pre>'A' // simple character'\u0041' // Unicode'\x0041' // unsigned short hexadecimal'\n' // escape sequence character</pre><p><b>String Type</b><p><pre>string a = "Heat";string a1 = "\\\\server\\fileshare\\helloworld.cs";string a2 = @"\\server\fileshare\helloworld.cs";Console.WriteLine(a1==a2); // Prints "True"string b1 = "First Line\r\nSecond Line";string b2 = @"First LineSecond Line";Console.WriteLine(b1==b2); // Prints "True"</pre><p><b>Types and Memory</b><p><b>Simple Types Are Value Types</b><p><pre>int i = 3;string s = i.ToString();// This is an explanatory version of System.Int32namespace System { struct Int32 { ... public string ToString() { return ...; } }}// This is valid code, but we recommend you use the int aliasSystem.Int32 i = 5;</pre><p><b>Value Types and Reference Types Side By Side</b><p><pre>// Reference-type declarationclass PointR { public int x, y;}// Value-type declarationstruct PointV { public int x, y;}class Test { static void Main() { PointR a; // Local reference-type variable, uses 4 bytes of // memory on the stack to hold address PointV b; // Local value-type variable, uses 8 bytes of // memory on the stack for x and y a = new PointR(); // Assigns the reference to address of new // instance of PointR allocated on the // heap. The object on the heap uses 8 // bytes of memory for x and y, and an // additional 8 bytes for core object // requirements, such as storing the // object's type synchronization state b = new PointV(); // Calls the value-type's default // constructor. The default constructor // for both PointR and PointV will set // each field to its default value, which // will be 0 for both x and y. a.x = 7; b.x = 7; }}// At the end of the method the local variables a and b go out of// scope, but the new instance of a PointR remains in memory until// the garbage collector determines it is no longer referenced ... PointR c = a; PointV d = b; c.x = 9; d.x = 9; Console.WriteLine(a.x); // Prints 9 Console.WriteLine(b.x); // Prints 7 }}</pre><p><b>Type System Unification</b><p><b>Value Types "Expand The Set Of Simple Types"</b><p><pre>int[] iarr = new int [1000];struct PointV { public int x, y}PointV[] pvarr = new PointV[1000];class PointR { public int x, y;}PointR[] prarr = new PointR[1000];for( int i=0; i<prarr.Length; i++ ) prarr[i] = new PointR();</pre><p><b>Boxing and Unboxing Value Types</b><p><pre>class Queue { ... void Enqueue(object o) {...} object Dequeue() {return ...}}Queue q = new Queue();q.Enqueue(9); // box the intint i = (int)q.Dequeue(); // unbox the int</pre><p><h4><u>Variables</u></h4><p><b>Definite Assignment</b><p><pre>using System;class Test { int v; // Constructors that initalize an instance of a Test public Test() {} // v will be automatically assigned to 0 public Test(int a) { // explicitly assign v a value v = a; } static void Main() { Test[] iarr = new Test [2]; // declare array Console.WriteLine(iarr[1]); // ok, elements assigned to null Test t; Console.WriteLine(t); // error, t not assigned }}</pre><p><b>Default Values</b><p><pre>int a = 1000000;int b = 1000000;// Check an expressionint c = checked(a*b);// Check every expression in a statement-blockchecked { ... c = a * b; ...}const int signedBit = unchecked((int)0x80000000);</pre><p><h4><u>Statements</u></h4><p><b>Expression Statements</b><p><pre>int x = 5 + 6; // assign resultx++; // side effectint y = Math.Min(x, 20); // side effect and assign resultMath.Min (x, y); // discards result, but ok, there is a side effectx == y; // error, has no side effect, and does not assign result</pre><p><b>Declaration Statements</b><p><pre>bool a = true;while(a) { int x = 5; if (x==5) { int y = 7; int x = 2; // error, x already defined } Console.WriteLine(y); // error, y is out of scope}const double speedOfLight = 2.99792458E08;speedOfLight+=10; // error</pre><p><b>Empty Statements</b><p><pre>while(!thread.IsAlive);</pre><p><b>Selection Statements</b><p><b>If-Else Statement</b><p><pre>int Compare(int a, int b) { if (a>b) return 1; else if (a<b) return -1; return 0;}</pre><p><b>Switch Statement</b><p><pre>void Award(int x) { switch(x) { case 1: Console.WriteLine("Winner!"); break; case 2: Console.WriteLine("Runner-up"); break; case 3: case 4: Console.WriteLine("Highly commended"); break; default: Console.WriteLine("Don't quit your day job!"); break; }}void Greet(string title) { switch (title) { case null: Console.WriteLine("And you are?"); goto default; case "King": Console.WriteLine("Greetings your highness"); // error, should specify break, otherwise... default : Console.WriteLine("How's it hanging?"); break; }}</pre><p><b>Loop Statements</b><p><b>While Loops</b><p><pre>int i = 0;while (i<5) { i++;}</pre><p><b>Do-While Loops</b><p><pre>int i = 0;do i++;while (i<5);</pre><p><b>For Loops</b><p><pre>for (int i=0; i<10; i++) Console.WriteLine(i);for (;;) Console.WriteLine("Hell ain't so bad");</pre><p><b>Foreach Loops</b><p><blockquote><b>foreach (</b> <i>type-value</i> <b>in</b> <i>IEnumerable</i> <b>)</b><br> <i>statement or statement-block</i></blockquote><p><pre>for (int i=0; i<dynamite.Length; i++) Console.WriteLine(dynamite [i]);foreach (Stick stick in dynamite) Console.WriteLine(stick);IEnumerator ie = dynamite.GetEnumerator();while (ie.MoveNext()) { Stick stick = (Stick)ie.Current; Console.WriteLine(stick);}</pre><p><b>Jump Statements</b><p><b>Break Statement</b><p><pre>int x = 0;while (true) { x++; if (x>5) break; // break from the loop}</pre><p><b>Continue Statement</b><p><pre>int x = 0;int y = 0;while (y<100) { x++; if ((x%7)==0) continue; // continue with next iteration y++;}</pre><p><b>Goto Statement</b><p><pre>int x = 4;start:x++;if (x==5) goto start;</pre><p><b>Return Statement</b><p><pre>int CalcX(int a) { int x = a * 100; return x; // return to the calling method with value}</pre><p><b>Throw Statement</b><p><pre>if (w==null) throw new Exception("w can't be null");</pre><p><h4><u>Organizing Types</u></h4><p><b>Namespaces</b><p><pre>namespace MyCompany.MyProduct.Drawing { class Point {int x, y, z} delegate void PointInvoker(Point p);}</pre><p><b>Nesting Namespaces</b><p><pre>namespace MyCompany { namespace MyProduct { namespace Drawing { class Point {int x, y, z} delegate void PointInvoker(Point p); } }}</pre><p><b>Using A Type With Its Fully Qualified Name</b><p><pre>namespace TestProject { class Test { static void Main() { MyCompany.MyProduct.Drawing.Point x; } }}</pre><p><b>Using Keyword</b><p><pre>namespace TestProject { using MyCompany.MyProduct.Drawing; class Test { static void Main() { Point x; } }}</pre><p><b>Aliasing Types and Namespaces</b><p><pre>using sys = System; // Namespace aliasusing txt = System.String; // Type aliasclass Test { static void Main() { txt s = "Hello, World!"; sys.Console.WriteLine(s); // Hello, World! sys.Console.WriteLine(s.GetType()); // System.String }}</pre><p><h4><u>Inheritance</u></h4><p><pre>class Location { // Implicitly inherits from object string name; // The constructor that initializes Location public Location(string name) { this.name = name; } public string Name {get {return name;}} public void Display() { Console.WriteLine(Name); }}class URL : Location { // Inherit from Location public void Navigate() { Console.WriteLine("Navigating to "+Name); } // The constructor for URL, which calls Location's constructor public URL(string name) : base(name) {}}:class Test { static void Main() { URL u = new URL("http://microsoft.com"); u.Display(); u.Navigate(); }}</pre><p><b>Class Conversions</b><p><pre>URL u = new URL();Location l = u; // upcastu = (URL)l; // downcast</pre><p><b>As Operator</b><p><pre>u = l as URL;</pre><p><b>Is Operator</b>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -