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

📄 cessentials_examples.htm

📁 国外CSharp入门书,包含的代码可作为学习CSharp的参考代码
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<pre>public class Object {  public Object() {...}  public virtual bool Equals(object o) {...}  public virtual int GetHashCode(){...}  public Type GetType(){...}  public virtual string ToString() {...}  protected virtual void Finalize() {...}  protected object MemberwiseClone() {...}}using System;class Beeblebrox {}class Test {  static void Main() {    string s = "Zaphod";    Beeblebrox b = new Beeblebrox();    Console.WriteLine(s); // Prints "Zaphod"    Console.WriteLine(b); // Prints "Beeblebrox"  }}</pre><p><b>Creating BCL-Friendly Types</b><p><pre>public class Point3D {  public int x, y, z;  public Point3D(int x, int y, int z) {    this.x=x; this.y=y; this.z=z; // Initialize data  }  public override bool Equals(object o) {    if (!(o is Point3D)) // Check for type equivalence      return false;    return (this==(Point3D)o); // Implemented by operator==  }  public static bool operator !=(Point3D lhs, Point3D rhs) {    return (!(lhs==rhs)); // Implemented by operator==  }  public static bool operator ==(Point3D lhs, Point3D rhs) {    return ((rhs.x==lhs.x) && (rhs.y==lhs.y) && (rhs.z==lhs.z));  }  public override int GetHashCode(){    return x^y^z;  }  public override string ToString() {    return String.Format("[{0},{1},{2}]", x, y, z);  }}using System;using System.Collections;public class Point3D {...}class TestPoint3D {  static void Main() {    // Uses ToString, prints "p1=[1,1,1] p2=[2,2,2] p3=[2,2,2]"    Point3D p1 = new Point3D(1,1,1);    Point3D p2 = new Point3D(2,2,2);    Point3D p3 = new Point3D(2,2,2);    Console.WriteLine("p1={0} p2={1} p3={2}", p1, p2, p3);    // Tests for equality to demonstrate Equals, == & !=    int i = 100;    Console.WriteLine(p1.Equals(i)); // Prints "False"    Console.WriteLine(p1==p2); // Prints "False"    Console.WriteLine(p2==p3); // Prints "True"    // Use a hashtable to store points (uses GetHashCode)    Hashtable ht = new Hashtable();    ht["p1"] = p1;     ht["p2"] = p2;    ht["p3"] = p3;    // Prints "p2=[2,2,2] p3=[2,2,2] p1=[1,1,1]"    foreach (DictionaryEntry de in ht)      Console.Write("{0}={1} ", de.Key, de.Value);    }}</pre><p><b>ICloneable Interface</b><p><pre>public interface ICloneable {  object Clone();}public class A : ICloneable {   int x;   public object Clone() {       return MemberwiseClone();   }}</pre><p><b>IComparable Interface</b><p><pre>interface IComparable {  int CompareTo(object o);}using System;using System.Collections;class MyType : IComparable {  public int x;  public MyType(int x) {    this.x = x;  }  public int CompareTo(object o) {    return x -((MyType)o).x;  }}class Test {  static void Main() {    ArrayList a = new ArrayList();    a.Add(new MyType(42));    a.Add(new MyType(17));    a.Sort();    foreach(MyType t in a)      Console.WriteLine(((MyType)t).x);   }}</pre><p><b>IFormattable Interface</b><p><pre>public interface IFormattable {  string Format(string format, IServiceObjectProvider sop);}</pre><p><h4><u>Math</u></h4><p><b>Language Support for Math</b><p><pre>struct Vector {  float direction;  float magnitude;  public Vector(float direction, float magnitude) {    this.direction = direction;    this.magnitude = magnitude;  }  public static Vector operator *(Vector v, float scale) {    return new Vector(v.direction, v.magnitude * scale);  }  public static Vector operator /(Vector v, float scale) {    return new Vector(v.direction, v.magnitude * scale);  }  ...}class Test {  static void Main() {  Vector [,] matrix = {{new Vector(1f,2f), new Vector(6f,2f)},                       {new Vector(7f,3f), new Vector(4f,9f)}};  for (int i=0; i&lt;matrix.GetLength(0); i++)    for (int j=0; j&lt;matrix.GetLength(1); j++)      matrix[i, j] *= 2f;}</pre><p><b>Special Types and Operators</b><p><b>Math Class</b><p><pre>using System;class Test {  static void Main() {    double a = 3;    double b = 4;    double C = Math.PI / 2;    double c = Math.Sqrt (a*a+b*b-2*a*b*Math.Cos(C));    Console.WriteLine("The length of side c is "+c);  }}</pre><p><b>Random Class</b><p><pre>Random r = new Random();Console.WriteLine(r.Next(50)); // return between 0 and 50</pre><p><h4><u>Strings</u></h4><p><b>Immutability of Strings</b><p><pre>string a = "Heat";string b = a.Insert(3, "r");Console.WriteLine(b); // Prints HeartIf you need a mutable string, see the StringBuilder class.</pre><p><b>String Interning</b><p><pre>string a = "hello";string b = "hello";Console.WriteLine(a == b); // TrueConsole.WriteLine(a.Equals(b)); // TrueConsole.WriteLine((object)a == (object)b); // True!!</pre><p><b>Formatting Strings</b><p><pre>using System;class TestFormatting {  static void Main() {    int i = 2;    decimal m = 42.73m;    string s = String.Format("Account {0} has {1:C}.", i, m);    Console.WriteLine(s); // Prints "Account 2 has $42.73"  }}</pre><p><b>Indexing Strings</b><p><pre>using System;class TestIndexing {  static void Main() {    string s = "Going down?";    for (int i=0; i&lt;s.Length; i++)      Console.WriteLine(s[i]); // Prints s vertically  }}</pre><p><b>Encoding Strings</b><p><pre>using System;using System.Text;class TestEncoding {  static void Main() {    byte[] ba = new byte[] { 67, 35, 32, 105, 115,                              32, 67, 79, 79, 76, 33 };    string s = Encoding.ASCII.GetString(ba);    Console.WriteLine(s);  }} </pre><p><b>StringBuilder Class</b><p><pre>using System;using System.Text;class TestStringBuilder {  static void Main() {    StringBuilder sb = new StringBuilder("Hello, ");    sb.Append("World");    sb[11] = '!';    Console.WriteLine(sb); // Hello, World!  }}</pre><p><h4><u>Collections</u></h4><p><b>ArrayList Class</b><p><pre>ArrayList a = new ArrayList();a.Add("Vernon");a.Add("Corey");a.Add("William");a.Add("Muzz");a.Sort();for(int i = 0; i &lt; a.Count; i++)   Console.WriteLine(a [i]);</pre><p><b>BitArray Class</b><p><pre>BitArray bits = new BitArray();bits.Length = 2;bits[1] = true;bits.Xor(bits); // Xor the array with itself</pre><p><b>Hashtable Class</b><p><pre>Hashtable ht = new Hashtable();ht["One"] = 1;ht["Two"] = 2;ht["Three"] = 3;Console.WriteLine(ht["Two"]); // Prints "2"</pre><p><b>Queue Class</b><p><pre>Queue q = new Queue();q.Enqueue(1);q.Enqueue(2);Console.WriteLine(q.Dequeue()); // Prints "1"Console.WriteLine(q.Dequeue()); // Prints "2"</pre><p><b>SortedList Class</b><p><pre>SortedList s = new SortedList();s["Zebra"] = 1;s["Antelope"] = 2;s["Eland"] = 3;s["Giraffe"] = 4;s["Meerkat"] = 5;s["Dassie"] = 6;s["Tokoloshe"] = 7;Console.WriteLine(s["Meerkat"]); // Prints "5" in 3 lookups</pre><b>Stack Class</b><p><pre>Stack s = new Stack();s.Push(1); // Stack = 1s.Push(2); // Stack = 1,2s.Push(3); // Stack = 1,2,3Console.WriteLine(s.Pop()); // Prints 3, Stack=1,2Console.WriteLine(s.Pop()); // Prints 2, Stack=1Console.WriteLine(s.Pop()); // Prints 1, Stack=</pre><p><b>StringCollection Class</b><p><pre>StringCollection sc = new StringCollection();sc.Add("s1");string[] sarr =  {"s2", "s3", "s4"};sc.AddRange(sarr);foreach (string s in sc)  Console.Write("{0} ", s); // s1 s2 s3 s4</pre><p><b>Collection Interfaces</b><p><pre>IEnumerablepublic interface IEnumerable {  IEnumerator GetEnumerator();}</pre><p><b>IEnumerator</b><p><pre>public interface IEnumerator {   bool MoveNext();   object Current {get;}   void Reset();}using System.Collections;public class MyCollection : IEnumerable {  // ...  public virtual IEnumerator GetEnumerator () {    return new MyCollection.Enumerator(this);  }  private class Enumerator : IEnumerator {     private MyCollection collection;    private int currentIndex = -1;    internal Enumerator (MyCollection collection) {      this.collection = collection;    }    public object Current {      get {        if (currentIndex == collection.Count)          throw new InvalidOperationException();        return collection [currentIndex];      }    }    public bool MoveNext () {      if (currentIndex &gt; collection.Count)        throw new InvalidOperationException();      return ++currentIndex &lt; collection.Count;    }    public void Reset () {      currentIndex = -1;    }  }}MyCollection mcoll = new MyCollection();...// Using foreach: substitute your typename for XXXforeach (XXX item in mcoll) {  Console.WriteLine(item);  ...}// Using IEnumerator: substitute your typename for XXXIEnumerator ie = myc.GetEnumerator();while (myc.MoveNext()) {  XXX item = (XXX)myc.Current;  Console.WriteLine(item);  ...}</pre><p><b>ICollection Interface</b><p><pre>public interface ICollection : IEnumerable {   void CopyTo(Array array, int index);   int Count {get;}   bool IsReadOnly {get;}   bool IsSynchronized {get;}   object SyncRoot {get;}}IComparer Interfacepublic interface IComparer {   int Compare(object x, object y);}</pre><p><b>IList Interface</b><p><pre>public interface IList : ICollection, IEnumerable {   object this [int index] {get; set}   int Add(object o);   void Clear();   bool Contains(object value);   int IndexOf(object value);   void Insert(int index, object value);   void Remove(object value);   void RemoveAt(int index);}</pre><p><b>IDictionary Interface</b><p><pre>public interface IDictionary : ICollection, IEnumerable {   object this [object key] {get; set};   ICollection Keys {get;}   ICollection Values {get;}   void Clear();   bool Contains(object value);   IDictionaryEnumerator GetEnumerator();   void Remove(object key);}</pre><p><b>IDictionaryEnumerator Interface</b><p><pre>public interface IDictionaryEnumerator : IEnumerator {   DictionaryEntry Entry {get;}   object Key {get;}   object Value {get;}}</pre><p><b>IHashCodeProvider Interface</b><p><pre>public interface IHashCodeProvider {   int GetHashCode(object o);}</pre><p><h3>Regular Expressions</h3><h4><u>Using Regular Expressions</u></h4><pre>// RegEx.cs - compile with /r:System.Text.RegularExpressions.dllusing System;using System.Text.RegularExpressions;class TestRegEx {  static void Main() {    string pat =@"(?&lt;1&gt;[^\+!?#]*)(?&lt;2&gt;\+)?[^!?#]*?(?&lt;3&gt;#)?(?&lt;4&gt;[!?]?!|\?)?(?&lt;3&gt;#)?";    string t = "e8=Q+#!!";    Regex regex = new Regex(pat);    Match m = regex.Match(t);    if(m == null)      System.Console.WriteLine("No Match");    else      System.Console.Write(        "Group 1 = "+ m.Group(1).ToString() + "\n" +        "Group 2 = "+ m.Group(2).ToString() + "\n" +        "Group 3 = "+ m.Group(3).ToString() + "\n" +        "Group 4 = "+ m.Group(4).ToString() + "\n");  }}Group 1 = e8=QGroup 2 = +Group 3 = #Group 4 = !!</pre><p><h4><u>Input/Output</u></h4><p><b>Concrete Stream-Derived Classes</b><p><pre>using System.IO;class Test {  static void Main() {    Stream s = new FileStream("foo.txt", Filemode.Create);    s.WriteByte("67");    s.WriteByte("35");    s.Close();  }}</pre><p><b>StreamReader and StreamWriter Classes</b><p><pre>using System.Text;using System.IO;class Test {  static void Main() {    Stream fs = new FileStream ("foo.txt", FileMode.Create);    StreamWriter sw = new StreamWriter(fs, Encoding.ASCII);    sw.Write("Hello!");    sw.Close();  }}</pre><p><b>StringReader and StringWriter Classes</b><p><pre>using System;using System.IO;using System.Text;class Test {  static void Main() {    StringBuilder sb = new StringBuilder();    StringWriter sw = new StringWriter(sb);    WriteHello(sw);    Console.WriteLine(sb);  }  static void WriteHello(TextWriter tw) {    tw.Write("Hello, String I/O!");  }}</pre><p><b>Directories and Files</b><p><pre>using System;using System.IO;class Test {   static void Main(string[] args) {      Stream s = File.OpenRead(args[0]);      StreamReader sr = new StreamReader(s);      Console.WriteLine(sr.ReadLine());      sr.Close();   }}</pre><p><h4><u>Networking</u></h4><p><b>Generic Request/Response Architecture</b><p><pre>// Snarf.cs - compile with /r:System.Net.dll// Run Snarf.exe &lt;http-uri&gt; to retrieve a web pageusing System;using System.IO;using System.Net;using System.Text;class Snarf {  static void Main(string[] args) {    // Retrieve the data at the URL with an WebRequest ABC    WebRequest req = WebRequestFactory.Create(args[0]);    WebResponse resp = req.GetResponse();    // Read in the data, performing ASCII-&gt;Unicode encoding    Stream s = resp.GetResponseStream();    StreamReader sr = new StreamReader(s, Encoding.ASCII);    string doc = sr.ReadToEnd();    Console.WriteLine(doc); // Print result to console  }}</pre><p><b>HTTP-Specific Support</b><p><pre>// ProbeSvr.cs - compile with /r:System.Net.dll// Run ProbeSvr.exe &lt;servername&gt; to retrieve the server typeusing System;using System.Net;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -