首页 > 开发 > 综合 > 正文

转阿土伯找到的文章:C# Coding Examples

2024-07-21 02:20:16
字体:
来源:转载
供稿:网友
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
   }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表