⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cessentials_examples.htm

📁 国外CSharp入门书,包含的代码可作为学习CSharp的参考代码
💻 HTM
📖 第 1 页 / 共 5 页
字号:
   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 &lt; 3; i++) {   matrixJ[i] = new int [4][];   for (int j = 0; j &lt; 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 &lt; vowels.Length; i++);// multi-dimensionalfor(int i = 0; i &lt; 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) &gt; 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) &gt; 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 &lt; 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 &lt; 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-&gt;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 &lt; 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 {  /// &lt;summary&gt;  /// The Foo method is called from  ///   &lt;see cref="Main"&gt;Main&lt;/see&gt;   /// &lt;/summary&gt;  /// &lt;mytag&gt;Secret stuff&lt;/mytag&gt;  /// &lt;param name="s"&gt;Description for s&lt;/param&gt;  static void Foo(string s) { Console.WriteLine(s); }  static void Main() { Foo("42"); }}  </pre><p><b>XML Documentation Files</b><p><pre>&lt;?xml version="1.0"?&gt;&lt;doc&gt;  &lt;assembly&gt;    &lt;name&gt;DocTest&lt;/name&gt;  &lt;/assembly&gt;  &lt;members&gt;    &lt;member name="M:MyClass.Foo(System.String)"&gt;      &lt;summary&gt;      The Foo method is called from        &lt;see cref="M:MyClass.Main"&gt;Main&lt;/see&gt;       &lt;/summary&gt;      &lt;mytag&gt;Secret stuff&lt;/mytag&gt;      &lt;param name="s"&gt;Description for s&lt;/param&gt;     &lt;/member&gt;  &lt;/members&gt;&lt;/doc&gt; </pre><b>Predefined XML Tags</b><p><u>&lt;summary&gt;, &lt;remarks&gt;</u><blockquote>&lt;summary&gt;<i>description</i>&lt;/summary&gt;&lt;remarks&gt;<i>description</i>&lt;/remarks&gt;</blockquote><u>&lt;param&gt;</u><blockquote>&lt;param name=<i>"name"</i>&gt;<i>description</i>&lt;/param&gt;</blockquote><u>&lt;returns&gt;</u><blockquote>&lt;returns&gt;<i>description</i>&lt;/returns&gt;</blockquote><u>&lt;exception&gt;</u><blockquote>&lt;exception [cref=<i>"type"</i>]&gt;<i>description</i>&lt;/exception&gt;</blockquote><u>&lt;permission&gt;</u><blockquote>&lt;permission [cref=<i>"type"</i>]&gt;<i>description</i>&lt;/permission&gt;</blockquote><u>The C# compiler supports the following XML tags.&lt;example&gt;, &lt;c&gt;, &lt;code&gt;</u><blockquote>&lt;example&gt;<i>description</i>&lt;/example&gt;&lt;c&gt;<i>code</i>&lt;/c&gt;&lt;code&gt;<i>code</i>&lt;/code&gt;</blockquote><u>&lt;see&gt;, &lt;seealso&gt;</u><blockquote>&lt;see cref=<i>"member"</i>&gt;<i>text</i>&lt;/see&gt;&lt;seealso cref=<i>"member"</i>&gt;<i>text</i>&lt;/seealso&gt;</blockquote><u>&lt;value&gt;</u><blockquote>&lt;value&gt;<i>description</i>&lt;/value&gt;</blockquote><u>&lt;paramref&gt;</u><blockquote>&lt;paramref name=<i>"name"</i>/&gt;</blockquote><u>&lt;list&gt;, &lt;para&gt;</u><blockquote><pre>&lt;list type=[ bullet | number | table ]&gt;  &lt;listheader&gt;    &lt;term&gt;<i>name</i>&lt;/term&gt;    &lt;description&gt;<i>description</i>&lt;/description&gt;  &lt;/listheader&gt;  &lt;item&gt;    &lt;term&gt;<i>name</i>&lt;/term&gt;    &lt;description&gt;<i>description</i>&lt;/description&gt;  &lt;/item&gt;&lt;/list&gt;&lt;para&gt;<i>text</i>&lt;/para&gt;</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 + -