📄 cessentials_examples.htm
字号:
bool CanDelete {get;} event EventHandler CanDeleteChanged;}</pre><p><b>Explicit Interface Implementation</b><p><pre>public interface IDesignTimeControl { ... object Delete();}public class TextBox : IDelete, IDesignTimeControl { ... void IDelete.Delete() {} object IDesignTimeControl.Delete() {...} // Note that explicitly implementing just one of them would // be enough to resolve the conflict}TextBox tb = new TextBox();IDesignTimeControl idtc = (IDesignTimeControl)tb;IDelete id = (IDelete)tb;idtc.Delete();id.Delete();</pre><p><b>Reimplementing An Interface</b><p><pre>public class RichTextBox : TextBox, IDelete { // TextBox's IDelete.Delete is not virtual (since explicit // interface implementations cannot be virtual) public void Delete() {}}</pre><p><b>Interface Conversions</b><p><pre>interface IDelete {...}interface IDesigntimeControl {...}class TextBox : IDelete, IDesignTimeControl {...}sealed class Timer : IDesignTimeControl {...}TextBox tb1 = new TextBox ();IDelete d = tb1; // implicit castIDesignTimeControl dtc = (IDesignTimeControl)d;TextBox tb2 = (TextBox)dtc;Timer t = (Timer)d; // illegal, a Timer can never implement IDelete</pre><p><h4><u>Arrays</u></h4><p><pre>char[] vowels = new char[] {'a','e','i','o','u'};Console.WriteLine(vowels [1]); // Prints "e"</pre><p><b>Multi-Dimensional Arrays</b><p><pre>// rectangularint [,,] matrixR = new int [3, 4, 5]; // creates 1 big cube// jaggedint [][][] matrixJ = new int [3][][];int [][][] matrixJ = new int [3][][];for (int i = 0; i < 3; i++) { matrixJ[i] = new int [4][]; for (int j = 0; j < 4; j++) matrixJ[i][j] = new int [5];} // assign an elementmatrixR [1,1,1] = matrixJ [1][1][1] = 7;</pre><p><b>Local and Field Array Declarations</b><p><pre>// single dimensionalfor(int i = 0; i < vowels.Length; i++);// multi-dimensionalfor(int i = 0; i < matrixR.GetLength(2); i++);</pre><p><b>Bounds Checking</b><p><h4><u>Enums</u></h4><p><pre>public enum Direction {North, East, West, South}Direction walls = Direction.East;[Flags]public enum Direction : byte { North=1, East=2, West=4, South=8}Direction walls = Direction.North | Direction.West;if((walls & Direction.North) != 0) System.Console.WriteLine("Can't go north!");Console.WriteLine(walls.Format()); // Displays "North|West"Console.WriteLine(walls); // Calls walls.ToString, displays "5"using System;public enum Toggle : byte { Off=0, On=1 }class TestEnum { static void Main() { Type t = Enum.GetUnderlyingType(typeof(Toggle)); Console.WriteLine(t); // Prints "Byte" bool bDimmed = Enum.IsDefined(typeof(Toggle), "Dimmed"); Console.WriteLine(bDimmed); // Prints "False" Toggle tog =(Switch)Enum.FromString(typeof(Toggle), "On"); Console.WriteLine(tog); // Prints "1" Console.WriteLine(tog.Format()); // Prints "On" object[] oa = Enum.GetValues(typeof(Toggle)); foreach(Toggle tog in oa) // Prints "On=1, Off=0" Console.WriteLine("{0}={1}", tog.Format(), tog); }}</pre><p><h4><u>Delegates</u></h4><p><pre>delegate bool Filter(string s);class Test { static void Main() { Filter f = new Filter(FirstHalfOfAlphabet); Display(new String [] {"Ant","Lion","Yak"}, f); } static bool FirstHalfOfAlphabet(string s) { return "N".CompareTo(s) > 0; } static void Display(string[] names, Filter f) { int count = 0; foreach(string s in names) if(f(s)) // invoke delegate Console.WriteLine("Item {0} is {1}", count++, s); }}</pre><p><b>Multicast Delegates</b><p><pre>delegate void MethodInvoker();class Test { static void Main() { new Test(); // prints "Foo","Goo" } Test() { MethodInvoker m = null; m += new MethodInvoker(Foo); m += new MethodInvoker(Goo); m(); } void Foo() { Console.WriteLine("Foo"); } void Goo() { Console.WriteLine("Goo"); }}Test { MethodInvoker m = null; m += new MethodInvoker(Foo); m -= new MethodInvoker(Foo); // m is now null}</pre><p><b>Delegates Compared With Interfaces</b><p><pre>interface IFilter { bool Filter(string s);}class Test { class FirstHalfOfAlphabetFilter : IFilter { public bool Filter(string s) { return ("N".CompareTo(s) > 0); } } static void Main() { FirstHalfOfAlphabetFilter f = new FirstHalfOfAlphabetFilter(); Display(new string [] {"Ant", "Lion", "Yak"}, f); } static void Display(string[] names, IFilter f) { int count = 0; foreach (string s in names) if (f.Filter(s)) Console.WriteLine("Item {0} is {1}", count++, s); }}</pre><p><h4><u>Events</u></h4><p><b>Defining a Delegate for an Event</b><p><pre>delegate void MoveEventHandler(object source, MoveEventArgs e);</pre><p><b>Storing Data for an Event with EventArgs</b><p><pre>public class MoveEventArgs : EventArgs { public int newPosition; public bool cancel; public MoveEventArgs(int newPosition) { this.newPosition = newPosition; }}</pre><p><b>Declaring and Firing an Event</b><p><pre>class Slider { int position; public event MoveEventHandler Move; public int Position { get { return position; } set { if (position != value) { // if position changed if (Move != null) { // if invocation list not empty MoveEventArgs args = new MoveEventArgs(value); Move(this, args); // fire event if (args.cancel) return; } position = value; } } }}</pre><p><b>Acting on an Event with Event Handlers</b><p><pre>class Form { static void Main() { Slider slider = new Slider(); // register with the Move event slider.Move += new MoveEventHandler(slider_Move); slider.Position = 20; slider.Position = 60; } static void slider_Move(object source, MoveEventArgs e) { if(e.newPosition < 50) Console.WriteLine("OK"); else { e.cancel = true; Console.WriteLine("Can't go that high!"); } }}</pre><p><b>Events As Properties</b><p><pre>public event MoveEventHandler Move { get { return (MoveEventHandler)myEventStorer["Move"]; } set { myEventStore ["Move"] = value; }}</pre><p><h4><u>Try Statements and Exceptions</u></h4><p><b>Exceptions</b><p><pre>public class File { ... public static StreamWriter CreateText(string s) { ... if (!Valid(s)) throw new IOException("Couldn't create...", ...); ... }}class Test { ... void Foo(object x) { StreamWriter sw = null; try { sw = File.CreateText("foo.txt"); sw.Write(x.ToString()); } catch(IOException ex) { Console.WriteLine(ex); } finally { if(sw != null) sw.Close(); } }}</pre><p><b>Catch Statement</b><p><pre>catch(IOException) { // don't specify variable Console.WriteLine("Couldn't create the foo!");}</pre><p><b>Catching System.Exception</b><p><pre>catch { Console.WriteLine("Couldn't create the foo!");}</pre><p><b>Specifying Multiple Catch Clauses</b><p><pre>try {...}catch (NullReferenceException) {...}catch (IOException) {...}catch {...}</pre><p><h4><u>Attributes</u></h4><p><b>Attribute Classes</b><p><pre>[Serializable]public class Foo {...}class SerializableAttribute : Attribute {...}[System.SerializableAttribute]public class Foo {...}</pre><p><b>Named and Positional Parameters</b><p><pre>[Obsolete("Use Bar class instead", IsError=true)]public class Foo {...}</pre><p><b>Attribute Targets</b><p><pre>[assembly:CLSCompliant(true)]</pre><p><b>Specifying Multiple Attributes</b><p><pre>[Serializable, Obsolete, CLSCompliant(false)]public class Bar {...}[Serializable] [Obsolete] [CLSCompliant(false)]public class Bar {...}[Serializable, Obsolete] [CLSCompliant(false)]public class Bar {...}</pre><p><h4><u>Unsafe Code and Pointers</u></h4><p><b>Unsafe Code</b><p><pre>unsafe void RedFilter(int[,] bitmap) { const int length = bitmap.Length; fixed (int* b = bitmap) { int* p = b; for(int i = 0; i < length; i++) *p++ &= 0xFF; }}</pre><p><b>Fixed Statement</b><p><pre>class Test { int x; static void Main() { Test test = new Test(); unsafe { fixed(int* p = &test.x) { // pins Test *p = 9; } System.Console.WriteLine(test.x); } }}</pre><p><b>Pointer to Member Operator</b><p><pre>struct Test { int x; unsafe static void Main() { Test test = new Test(); Test* p = &test; p->x = 9; System.Console.WriteLine(test.x); }}</pre><p><b>The stackalloc Keyword</b><p><pre>int* a = stackalloc int [10];for (int i = 0; i < 10; ++i) Console.WriteLine(a[i]); // print raw memory</pre><p><b>Pre-Processor Directives</b><p><pre>#define DEBUGclass MyClass { int x; void Foo() { # if DEBUG Console.WriteLine("Testing: x = {0}", x); # endif ...}#define DEBUG = true</pre><p><h4><u>XML Documentation</u></h4><p><b>C/C++-Style Comments</b><p><pre>int x = 3; // this is a commentMyMethod(); /* this is acomment that spans two lines */</pre><p><b>Documentation Comments</b><p><pre>// Filename: DocTest.csusing System;class MyClass { /// <summary> /// The Foo method is called from /// <see cref="Main">Main</see> /// </summary> /// <mytag>Secret stuff</mytag> /// <param name="s">Description for s</param> static void Foo(string s) { Console.WriteLine(s); } static void Main() { Foo("42"); }} </pre><p><b>XML Documentation Files</b><p><pre><?xml version="1.0"?><doc> <assembly> <name>DocTest</name> </assembly> <members> <member name="M:MyClass.Foo(System.String)"> <summary> The Foo method is called from <see cref="M:MyClass.Main">Main</see> </summary> <mytag>Secret stuff</mytag> <param name="s">Description for s</param> </member> </members></doc> </pre><b>Predefined XML Tags</b><p><u><summary>, <remarks></u><blockquote><summary><i>description</i></summary><remarks><i>description</i></remarks></blockquote><u><param></u><blockquote><param name=<i>"name"</i>><i>description</i></param></blockquote><u><returns></u><blockquote><returns><i>description</i></returns></blockquote><u><exception></u><blockquote><exception [cref=<i>"type"</i>]><i>description</i></exception></blockquote><u><permission></u><blockquote><permission [cref=<i>"type"</i>]><i>description</i></permission></blockquote><u>The C# compiler supports the following XML tags.<example>, <c>, <code></u><blockquote><example><i>description</i></example><c><i>code</i></c><code><i>code</i></code></blockquote><u><see>, <seealso></u><blockquote><see cref=<i>"member"</i>><i>text</i></see><seealso cref=<i>"member"</i>><i>text</i></seealso></blockquote><u><value></u><blockquote><value><i>description</i></value></blockquote><u><paramref></u><blockquote><paramref name=<i>"name"</i>/></blockquote><u><list>, <para></u><blockquote><pre><list type=[ bullet | number | table ]> <listheader> <term><i>name</i></term> <description><i>description</i></description> </listheader> <item> <term><i>name</i></term> <description><i>description</i></description> </item></list><para><i>text</i></para></pre></blockquote><p> <b>Type or Member Cross-References</b><p><pre>// Namespaces do not have independent signaturesnamespace NS { // T:NS.MyClass class MyClass { // F:NS.MyClass.aField string aField; // P:NS.MyClass.aProperty short aProperty {get {...} set {...}} // T:NS.MyClass.NestedType class NestedType {...}; // M:NS.MyClass.X() void X() {...} // M:NS.MyClass.Y(System.Int32,System.Double@,System.Decimal@) void Y(int p1, ref double p2, out decimal p3) {...} // M:NS.MyClass.Z(System.Char[],System.Single[0:,0:]) void Z(char[] p1, float[,] p2) {...} // M:NS.MyClass.op_Addition(NS.MyClass,NS.MyClass) public static MyClass operator+(MyClass c1, MyClass c2) {...} // M:NS.MyClass.op_Implicit(NS.MyClass)~System.Int32 public static implicit operator int(MyClass c) {...} // M:NS.MyClass.#ctor MyClass() {...} // M:NS.MyClass.Finalize ~MyClass() {...} // M:NS.MyClass.#cctor static MyClass() {...} }}</pre><p><h3>Programming the .NET Framework</h3><h4><u>Common Types</u></h4><b>Object Class</b><p>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -