首 页 | 报价 | 活动 | 硬件 | 数码 | 整机 | 手机 | 新闻 | DIY | 导购 | 学院 | 专题 | 市场地图 | 商家名录 | 商情 | 论坛 | 下载 | 电视 | 算命 | 读心术 | 游戏
您现在的位置: 首页>学院>开发平台>VC/C#>正文
转阿土伯找到的文章:C# Coding Examples
文章来源: 文章作者: 发布时间:2006-03-28



  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 i


上一篇:转:设计模式Singleton(例子是C#的)
下一篇:转贴: MSDN 访谈录之C#编程一 rainbow(翻译)
精彩推荐     
关于我们 | 广告服务 | 建站服务 | 招贤纳士 | 会员服务 | 网站地图 | RSS订阅 | 联系我们

实名:中原硅谷网、电脑报价、电脑硬件报价 客服电话:0371-63659150

中原硅谷网 WWW.ZZIT.COM.CN&WWW.ZZ-IT.COM
2003-2007 版权所有