教程中国
PHOTOSHOP CS9.0中文版 MAYA 8.5 FOR WINDOWS Corel Painter v9.0 Flash MX2004 中文版 Illustrator cs2 中文版
VC++6.0含sp6 中英文版 VB6.0 +sp6 简体中文版 Borland Delphi 7汉化版 MSDN for vb6.0中文版 Visual Studio 2005简体
教程中国下属 文件存储共享专家BIBIDU.COM 提供大型软件,教材,源码,电影,音乐,图书等下载 更多精品请点此进入
  您目前所在位置: 教程中国 >> .NET类 >> ASP.NET >> 转阿土伯找到的文章:C# Coding Examples RSS订阅
转阿土伯找到的文章:C# Coding Examples
教程(视频,书籍)下载:  ASP.NET AutoCAD 数据库 C# ASP java photoshop 网页设计 delphi 3dmax Flash C++ VB 张孝祥 实例   更多请进入BIBIDU搜索
IT搜索引擎   
C# Codeing Examples
--------------------------------------------------------------------------------
Provided by Jeffrey Richter
Jeffrey Richter (JeffreyRichter.com) is a cofounder of Wintellect (Wintellect.com), a software consulting, education, and development firm that specializes in .NET, Windows, and COM programming. Jeffrey is also a contributing editor to MSDN Magazine and is the author of two Microsoft Press books: Programming Applications for Microsoft Windows and Programming Server-Side Applications for Microsoft Windows.

Jeffrey is a design and programming consultant for many companies including Microsoft, Intel, and DreamWorks. He is currently writing a book tentatvively titled: Programming Applications for the .NET Frameworks.

The following represents the short bits of code-fragments that Jeffrey had with him in order to illustrate various ASPects of C# that he felt might be usefull to communicate during this episode. While we didn't get a chance to work through many of these examples, he graciously has provided us with his notes so that you might be able to look at them and get some additional ideas about the features and capabilities of C#.

Members Only
Everything is a member of a type. There are no global methods or variables. Note that the following "Hello World" sample application defines its "Main" function as part of a class:
using System;

class App {
   public static void Main(string[] args) {
      Console.WriteLine("Hello World");
   }
}

For everything, there is an exception
Exception support in C# is a first-class citizen of the language itself. The following example illustrates the use of the try/catch/finally process for detecting and reacting to errors. Note that the "finally" condition is guaranteed to be run regardless of the error situation.

Also notice the string @"C:\NotThere.txt", this illustrates the use of a '"Verbatim String" (That is what the "@" signifies) in which you don't need to worry about putting in two \\'s in order too get it to display one.
using System;
using System.IO;

public class App {
   public static void Main() {
      FileStream fs = null;
      try {
         fs = new FileStream(@"C:\NotThere.txt", FileMode.Open);
      }
      catch (Exception e) {
         Console.WriteLine(e.Message);
      }
      finally {
         if (fs != null) fs.Close();
      }
   }
}

Getting off to a good start
This example shows a few different ASPects of how to pre-initialize values:
class MyCollection {
   Int32 numItemsInCollection = 0;
   DateTime creationDateTime = new DateTime.Now();

   // This even works for static fields
   static Int32 numObjInstances = 0;
   ...
}

Filling all your buckets
This example shows various ASPects of defining, initializing, and using arrays.
static void ArrayDemo() {
   // Declare a reference to an array
   Int32[] ia; // defaults to null
   ia = new Int32[100];
   ia = new Int32[] { 1, 2, 3, 4, 5 };

   // Display the array's contents
   foreach (Int32 x in ia)
      Console.Write("{0} ", x);


   // Working with multi-dimensional arrays
   StringBuilder[,] sa = new StringBuilder[10][5];
   for (int x = 0; x < 10; x++) {
      for (int y = 0; y < 5; y++) {
         sa[x][y] = new StringBuilder(10);
      }
   }

   // Working with jagged arrays (arrays of arrays)
   Int32 numPolygons = 3;
   Point[][] polygons = new Point[numPolygons][];
   polygons[0] = new Point[3]  { ... };
   polygons[1] = new Point[5]  { ... };
   polygons[2] = new Point[10] { ... };
}

When Private things are Public
This example shows how to properly abstract a type's data. The data fields are private and are exposed via public properties. It also shows how to throw an exception.
class Employee {
   private String _Name;
   private Int32  _Age;
   public String Name {
      get { return(_Name); }
      set { _Name = value; } // 憊alue?identifies new value
   }

   public Int32 Age {
      get { return(_Age); }
      set {
         if (value <= 0)    // 憊alue?identifies new value
            throw(new ArgumentException("Age must be >0"));
         _Age = value;
      }
   }
}

// Usage:
e.Age = 36;       // Updates the age
e.Age = -5;       // Throws an exception

Castaways
This code demonstrates how to use C#'s is and as operators to perform type safe casting operations.
Object o = new Object();
Boolean b1 = (o is Object); // b1 is True
Boolean b2 = (o is String); // b2 is False

// Common usage:
if (o is String) {         // CLR checks type
   String s = (String) o;  // CLR checks type again
   ...
}


Object o = new Object();  // Creates a new Object
Jeff j = o as Jeff;       // Casts o to a Jeff, j is null
j.ToString();  // throws NullReferenceException

// Common usage (simplifies code above):
String s = o as String;   // CLR checks type (once)
if (s != null) {
   ...
}

A new way to spin a loop
Using the "foreach" statement can sometimes simplify your code. This example shows iterating through a set with either a "while" statement or with a "foreach" statement.
void WithoutForeach () {
   // Construct a type that manages a set of items
   SetType st = new SetType(...);

   // To enumerate items, request the enumerator
   IEnumerator e = st.GetEnumerator();

   // Advance enumerator抯 cursor until no more items
   while (e.MoveNext()) {
      // Cast the Current item to the proper type
      ItemType it = (ItemType) e.Current;

      // Use the item anyway you want
      Console.WriteLine("Do something with this item: " + it);
   }
}

void WithForeach () {
   // Construct a type that manages a set of items
   SetType st = new SetType(...);

   foreach (ItemType it in st) {
      // Use the item anyway you want
      Console.WriteLine("Do something with this item: " + it);
   }
}

Check your attitude at the door
The "checked" and "unchecked" keywords provide control of overflow exceptions when working with numbers. The following example illustrates how this can be used:
Byte b = 100;
b = (Byte) checked(b + 200);     // b contains 44
b = checked((Byte)(b + 200));    // OverflowException on cast

checked {
   Byte b = 100;
   b = (Byte) (b + 200);         // OverflowException
}

UInt32 Invalid = unchecked((UInt32) -1);  // OK

Int32 CalculateChecksum(Byte[] ba) {
   Int32 Checksum = 0;
   foreach(Byte b in ba) {
      unchecked {
         Checksum += b;
      }
   }
   return(Checksum);
}

Keeps going... and going.. and going...
Using a "params" parameter allows a method to easily accept a variable number of parameters. A method that uses a "params" parameter must use it as the last (or only) input parameter, and it can only be a single-dimension array:
Int64 Sum(params Int32[] values) {
    Int64 sum = 0;
    foreach (Int32 val in values)
        sum += val;
    return(sum);
}

void SomeMethod() {
    Int64 result = Sum(1, 2, 3, 4, 5);

    result = Sum(new Int32[] { 1, 2, 3, 4, 5 });  // Also works
}

Some bits can't be twiddled
Here is an example that illustrates how to work with "const" and "readonly" fields:
class MyType {
   // NOTE: const fields are always considered 'static'
   // const fields must be calculated at compile-time
   public const int maxEntries = 33;    
   public const String path = @"C:\Test.dat";    // Verbatim string
   ...
}

class MyType {
   public static readonly Employees[] employees = new Employees[100];
   public readonly Int32 employeeIndex;

   public MyType(Int32 employeeIndex) {
      this.employeeIndex = employeeIndex;
   }

   void SomeMethod() {
      this.employeeIndex = 10;    // Compiler error
   }



来源:upschool.com.cn
作者:
关键字:转阿土伯找到,文章,Coding,Examples
发表日期:2005-12-23

网页显示有限 阅读全文请下载本文完整版WORD文档

上一篇:转重粒子空间:C#,自然的进步   下一篇:转载《可怕的 C# !〉


2009-1-9 19:43:37
本文的相类似文章
  • 网文快捕:收集文章的利器使用
  • Oracle优化经典文章--磁盘I/O和碎片篇
  • Oracle优化经典文章------索引原理篇
  • EBOOK文章类软件的破解
  • 经典的菜鸟学习的入侵文章
  • 用 VB 实现新闻眼(提取搜狐的当天新闻),刚写的文章(准备投稿用的),大家先看为快吧,再提点见意!!
  • 别人编写的,自己加工过的qmail安装文章,在RH9上绝对没问题
  • 先来一篇文章试试
  • Linux Shell(也算是我的shell入门文章吧)
  • 第一篇Blog文章
  • 在学习中进步 在进步中成长 教程中国相随您的成长之路
    华腾联合科技股份有限公司版权所有
    广告联系:Rosibo@163.com