C#速成原文出处:http://www.codeguru.com/cs_syntax/CSharp.html
C#速成
原作者:Aisha Ikram
C#速成在一些术语上我尽量做到与MSDN的中文资料所述术语保持一致
C#速成
C#速成使用环境: .NET, C#, Win XP, Win 
2000 
C#速成
C#速成绪论
C#速成C#是这样的一种语言,具有C
++的特点,象Java一样的编程风格, 并且象Basic一样的快速开发模型。如果你已经知道了C++,本文会在不到一个小时的时间内让你迅速掌握C#的语法。熟悉Java的括会更好,因为Java的程序结构、打包(Packages)和垃圾收集的概念有助于你更快的了解C#。因此在讨论C#的构造时,我会假定你了解C++
C#速成
C#速成本文会讨论C#语言的构造与特点,同时会采取简洁的和你能理解的方式使用些代码示例,我们会尽量让你能稍微看看这些代码就能理解这些概念。
C#速成
C#速成注意:本文不是为C#高手(C# gurus)所写. 这是针对在C#学习上还是初学者的文章。
C#速成
C#速成下面是将要讨论的C#问题的目录:
C#速成
C#速成程序结构 
C#速成命名空间
C#速成数据类型
C#速成变量
C#速成运算符和表达式
C#速成枚举
C#速成语句(Statements )
C#速成类(Classes)和结构(Structs)
C#速成修饰符(Modifiers)
C#速成属性(Properties)
C#速成接口(Interfaces)
C#速成方法参数(Function Parameters)
C#速成数组(Arrays)
C#速成索引器(Indexers)
C#速成装箱及拆箱操作
C#速成委托(Delegates)
C#速成继承和多态
C#速成
C#速成下面的内容将不会在被讨论之列:
C#速成
C#速成C
++与C#谁更通用
C#速成诸如垃圾回收、线程以及文件处理等概念
C#速成数据的类型转换
C#速成异常处理
C#速成.NET库
C#速成
C#速成
-------------------
C#速成程序结构
C#速成
-------------------
C#速成这一点象C
++,C#是一种对大小写字母敏感的语言,分号“;”是语句间的分隔符。与C++不同的是,C#当中声明代码文件(头文件)与实现代码文件(cpp文件)不是独立存在的,所有代码(类声明和类实现)都位于一个扩展名为cs的文件内。
C#速成
C#速成让我们瞧瞧C#当中的 Hello world 程序是怎样的。
C#速成
C#速成
using System;
C#速成
C#速成
namespace MyNameSpace
C#速成
{
C#速成
C#速成
class HelloWorld
C#速成
{
C#速成    
static void Main(string[] args)
{
C#速成        Console.WriteLine (
"Hello World");
C#速成     }

C#速成}

C#速成
C#速成}

C#速成
C#速成在C#当中的每样东西都被封装到一个类中,C#的类又被封装到一个命名空间当中(就象一个文件夹中的文件)。类似于 C
++,main方法是你的程序的入口点。C++的main函数调用名称是"main",而C#的main函数是以大写字母M为起点的名称是"Main"
C#速成
C#速成没有必要把分号分隔符放在类语句块或者结构定义语句块后。这在C
++当中被要求,但在C#当中却不是。
C#速成
C#速成
-------------------
C#速成命名空间
C#速成
-------------------
C#速成每一个类都被包装进一个命名空间。命名空间的概念与C
++的完全相同,但在C#当中使用命名空间的频率较C++还高。你可以使用点限定符(dot qulifier)访问一个类。在上面的hello world程序当中MyNameSpace就是一个命名空间。
C#速成
C#速成现在思考这样的一个问题,你想从某些别的类的命名空间当中来访问HelloWorld这个类该如何操作。
C#速成这有一个例子:
C#速成
C#速成
using System;
C#速成
namespace AnotherNameSpace
{
C#速成    
class AnotherClass
{
C#速成        
public void Func()
{
C#速成            Console.WriteLine (
"Hello World");
C#速成        }

C#速成    }

C#速成}

C#速成
C#速成现在,从你的HelloWorld类里你能象这样去访问上面的这个AnotherNameSpace的命名空间:
C#速成
C#速成
using System;
C#速成
using AnotherNameSpace;    // you will add this using statement
C#速成
namespace MyNameSpace
{
C#速成
class HelloWorld
{
C#速成    
static void Main(string[] args)
{
C#速成        AnotherClass obj 
= new AnotherClass();
C#速成        obj.Func();
C#速成    }

C#速成}

C#速成}

C#速成
C#速成在.NET库当中,System是位于顶层的命名空间,别的命名空间都存在这个命名空间之下。默认状态下,存在一个全局的命名空间,因此一个在命名空间外定义的类将直接在这个全局命名空间之下;因此,你能在没有任何点限定符的情况下访问这个类。
C#速成
C#速成你也可以象下面这样定义嵌套的命名空间。
C#速成
C#速成Using
C#速成C
++当中的"#include"指示被C#的"using"关键字取代,它后面跟着一个命名空间的名字。正如上面的"using System""System"是别的所有被封装的命名空间和类中最底层的命名空间。所有对象的基类都是System命名空间内的Object类派生的。
C#速成
C#速成
-------------------
C#速成变量
C#速成
-------------------
C#速成除以下并别外,C#当中的变量几乎与C
++同:
C#速成
C#速成与C
++不同,C#变量被访问之前必须被初始化;否则编译时会报错。因此,访问一个未初始化变量是不可能的事。
C#速成C#中你不会访问到一个不确定的指针。(译者注:严格说起来C#已经把指针概念异化,限制更严格。所以有些资料上会说C#取消了指针概念)
C#速成一个超出数组边界的表达式是不可访问的。
C#速成C#中没有全局的的变量或全局函数,全局方式的操作是通过静态函数和静态变量来实现的。
C#速成
C#速成
C#速成
-------------------
C#速成数据类型
C#速成
-------------------
C#速成所有C#数据类型都派生自基类Object。这里有两类数据类型:
C#速成
C#速成基本型
/内置型 用户自定义型
C#速成
C#速成下面一个C#内置类型列表:
C#速成
C#速成类型 字节数 解释
C#速成
byte 1 无符号字节型
C#速成
sbyte 1 有符号字节型
C#速成
short 2 有符号短字节型
C#速成
ushort 2 无符号短字节型
C#速成
int 4 有符号整型
C#速成
uint 4 无符号整型
C#速成
long 8 有符号长整型
C#速成
ulong 8 无符号长整型
C#速成
float 4 浮点数
C#速成
double 8 双精度数
C#速成
decimal 8 固定精度数
C#速成
string unicode字串型
C#速成
char unicode字符型
C#速成
bool 真假布尔型
C#速成
C#速成注意:C#当中的类型范围与C
++有所不同;例如,C++的long型是4个字节,而在C#当中是8个字节。同样地,bool型和string型都不同于C++。bool型只接受true和false两种值。不接受任何整数类型。
C#速成
C#速成用户定义类型包括:
C#速成
C#速成类类型(
class)
C#速成结构类型(
struct)
C#速成接口类型(
interface)
C#速成
C#速成数据类型的内存分配形式的不同又把它们分成了两种类型:
C#速成
C#速成值类型(value Types)
C#速成引用类型(Reference Types)
C#速成
C#速成值类型:
C#速成值类型数据在栈中分配。他们包括:所有基本或内置类型(不包括string类型)、结构类型、枚举类型(
enum type)
C#速成
C#速成引用类型:
C#速成引用类型在堆中分配,当它们不再被使用时将被垃圾收集。它们使用new运算符来创建,对这些类型而言,不存在C
++当中的delete操作符,根本不同于C++会显式使用delete这个运算符去释放创建的这个类型。C#中,通过垃圾收集器,这些类型会自动被收集处理。
C#速成
C#速成引用类型包括:类类型、接口类型、象数组这样的集合类型类型、字串类型、枚举类型
C#速成
C#速成枚举类型与C
++当中的概念非常相似。它们都通过一个enum关键字来定义。
C#速成
C#速成示例:
C#速成
C#速成
enum Weekdays
{
C#速成  Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
C#速成}

C#速成
C#速成类类型与结构类型的比较
C#速成除了在内存分配形式上外,类与结构的概念完全与C
++相同。类的对象被分配在堆中,并且通过new来创建,结构也是被new创建但却被分配在栈当中。C#当中,结构型适于快速访问和拥有少量成员的数据类型。如果涉及量较多,你应该创建一个类来实现他。
C#速成(译者注:这与堆和栈内存分配结构的特点有关。简而言之,栈是一种顺序分配的内存;堆是不一定是连续的内存空间。具体内容需要大家参阅相关资料)
C#速成
C#速成示例:
C#速成
C#速成
struct Date
{
C#速成    
int day;
C#速成    
int month;
C#速成    
int year;
C#速成}

C#速成
C#速成
class Date
{
C#速成    
int day;
C#速成    
int month;
C#速成    
int year;
C#速成    
string weekday;
C#速成    
string monthName;
C#速成    
public int GetDay()
{
C#速成        
return day;
C#速成    }

C#速成    
public int GetMonth()
{
C#速成        
return month;
C#速成    }

C#速成    
public int GetYear()
{
C#速成        
return year;
C#速成    }

C#速成    
public void SetDay(int Day)
{
C#速成        day 
= Day ;
C#速成    }

C#速成    
public void SetMonth(int Month)
{
C#速成        month 
= Month;
C#速成    }

C#速成    
public void SetYear(int Year)
{
C#速成        year 
= Year;
C#速成    }

C#速成    
public bool IsLeapYear()
{
C#速成        
return (year/4 == 0);
C#速成    }

C#速成    
public void SetDate (int day, int month, int year)
{
C#速成    }

C#速成    C#速成
C#速成}

C#速成
C#速成
C#速成
C#速成
-------------------
C#速成属性
C#速成
-------------------
C#速成如果你熟悉C
++面象对象的方式,你就一定有一个属性的概念。在上面示例当中,以C++的观点来看,Data类的属性就是day、month和year。用C#方式,你可以把它们写成Get和Set方法。C#提供了一个更方便、简单、直接的方式来访问属性。
C#速成
C#速成因此上面的类可以被写成:
C#速成
C#速成
using System;
C#速成
class Date
{
{
{
C#速成            
return day;
C#速成        }

{
C#速成            day 
= value;
C#速成        }

C#速成    }

C#速成    
int day;
C#速成
{
{
C#速成            
return month;
C#速成        }

{
C#速成            month 
= value;
C#速成        }

C#速成    }

C#速成    
int month;
C#速成
{
{
C#速成            
return year;
C#速成        }

{
C#速成            year 
= value;
C#速成        }

C#速成    }

C#速成    
int year;
C#速成
C#速成    
public bool IsLeapYear(int year)
{
C#速成        
return year%4== 0 ? truefalse;
C#速成    }

C#速成    
public void SetDate (int day, int month, int year)
{
C#速成        
this.day   = day;
C#速成        
this.month = month;
C#速成        
this.year  = year;
C#速成    }

C#速成}

C#速成
C#速成你可在这里得到并设置这些属性:
C#速成
C#速成
class User
{
C#速成   
public static void Main()
{
C#速成        Date date 
= new Date();
C#速成        date.Day 
= 27;
C#速成        date.Month 
= 6;
C#速成        date.Year 
= 2003;
C#速成        Console.WriteLine(
"Date: {0}/{1}/{2}", date.Day,
C#速成                                               date.Month,
C#速成                                               date.Year);
C#速成    }

C#速成}

C#速成
C#速成
C#速成
C#速成
C#速成
-------------------
C#速成修饰符
C#速成
-------------------
C#速成你必须已经知道public、
private、protected这些常在C++当中使用的修饰符。这里我会讨论一些C#引入的新的修饰符。
C#速成
C#速成
readonly(只读)
C#速成readonly修饰符仅在类的数据成员中使用。正如这名字所提示的,
readonly 数据成员仅能只读,它们只能在构造函数或是直接初始化操作下赋值一次。readonly与const数据成员不同,const 要求你在声明中初始化,这是直接进行的。看下面的示例代码:
C#速成
C#速成
class MyClass
{
C#速成    
const int constInt = 100;    //直接初始化
C#速成
    readonly int myInt = 5;      //直接初始化
C#速成
    readonly int myInt2;     //译者注:仅做声明,未做初始化
C#速成
    
C#速成    
public MyClass()
{
C#速成        myInt2 
= 8;              //间接的
C#速成
    }
C#速成    
public Func()
{
C#速成        myInt 
= 7;               //非法操作(译者注:不得赋值两次)
C#速成
        Console.WriteLine(myInt2.ToString());
C#速成    }

C#速成    
C#速成}

C#速成
C#速成
sealed(密封)
C#速成密封类不允许任何类继承,它没有派生类。因此,你可以对你不想被继承的类使用sealed关键字。
C#速成
C#速成
sealed class CanNotbeTheParent
{
C#速成    
int a = 5;
C#速成}

C#速成
C#速成
unsafe(不安全)
C#速成你可使用unsafe修饰符来定义一个不安全的上下文。在不安全的上下文里,你能写些如C
++指针这样的不安全的代码。看下面的示例代码:
C#速成
C#速成
public unsafe MyFunction( int * pInt, double* pDouble)
{
C#速成    
int* pAnotherInt = new int;
C#速成    
*pAnotherInt  = 10;
C#速成    pInt 
= pAnotherInt;
C#速成    C#速成
C#速成    
*pDouble = 8.9;
C#速成}

C#速成
C#速成
C#速成
C#速成
C#速成
-------------------
C#速成
interface(接口)
C#速成
-------------------
C#速成
C#速成如果你有COM方面的概念,你会立亥明白我要谈论的内容。一个接口就是一个抽象的基类,这个基类仅仅包含功能描述,而这些功能的实现则由子类来完成。C#中你要用interface关键字来定义象接口这样的类。.NET就是基于这样的接口上的。C#中你不支持C
++所允许的类多继承(译者注:即一个派生类可以从两个或两个以上的父类中派生)。但是多继承方式可以通过接口获得。也就是说你的一个子类可以从多个接口中派生实现。
C#速成
C#速成
using System;
C#速成
interface myDrawing
{
C#速成    
int originx
{
C#速成        
get;
C#速成        
set;
C#速成    }

C#速成    
int originy
{
C#速成        
get;
C#速成        
set;
C#速成    }

C#速成    
void Draw(object shape);
C#速成}

C#速成
C#速成
class Shape: myDrawing
{
C#速成    
int OriX;
C#速成    
int OriY;
C#速成
C#速成    
public int originx
{
{
C#速成            
return OriX;
C#速成        }

{
C#速成            OriX 
= value;
C#速成        }

C#速成    }

C#速成    
public int originy
{
{
C#速成            
return OriY;
C#速成        }

{
C#速成            OriY 
= value;
C#速成        }

C#速成    }

C#速成    
public void Draw(object shape)
{
C#速成        C#速成    
// do something
C#速成
    }
C#速成    
C#速成    
// class's own method
C#速成
    public void MoveShape(int newX, int newY)
{
C#速成    C#速成..
C#速成    }

C#速成    
C#速成}

C#速成
C#速成
C#速成
C#速成
C#速成
-------------------
C#速成Arrays(数组)
C#速成
-------------------
C#速成
C#速成C#中的数组比C
++的表现更好。数组被分配在堆中,因此是引用类型。你不可能访问超出一个数组边界的元素。因此,C#会防止这样类型的bug。一些辅助方式可以循环依次访问数组元素的功能也被提供了,foreach就是这样的一个语句。与C++相比,C#在数组语法上的特点如下:
C#速成
C#速成方括号被置于数据类型之后而不是在变量名之后。
C#速成创建数组元素要使用new操作符。
C#速成C#支持一维、多维以及交错数组(数组中的数组)。
C#速成
C#速成示例:
C#速成
C#速成    
int[] array = new int[10];              // 整型一维数组
C#速成
    for (int i = 0; i < array.Length; i++)
C#速成        array[i] 
= i; 
C#速成
C#速成    
int[,] array2 = new int[5,10];          // 整型二维数组
C#速成
    array2[1,2= 5;
C#速成
C#速成    
int[,,] array3 = new int[5,10,5];       // 整型的三维数组
C#速成
    array3[0,2,4= 9;
C#速成
C#速成    
int[][] arrayOfarray = = new int[2];    // 整型交错数组(数组中的数组)
C#速成
    arrayOfarray[0= new int[4]; 
;
C#速成
C#速成
C#速成
C#速成
C#速成
-------------------
C#速成索引器
C#速成
-------------------
C#速成
C#速成索引器被用于写一个访问集合元素的方法,集合使用
"[]"这样的直接方式,类似于数组。你所要做的就是列出访问实例或元素的索引清单。类的属性带的是输入参数,而索引器带的是元素的索引表,除此而外,他们二者的语法相同。
C#速成
C#速成示例:
C#速成
C#速成注意:CollectionBase是一个制作集合的库类。List是一个protected型的CollectionBase成员,储存着集合清单列表。
C#速成
class Shapes: CollectionBase
{
C#速成    
public void add(Shape shp)
{
C#速成        List.Add(shp);
C#速成    }

C#速成
C#速成    
//indexer
C#速成
    public Shape this[int index]
{
{
C#速成            
return (Shape) List[index];
C#速成        }

{
C#速成            List[index] 
= value ;
C#速成         }

C#速成     }

C#速成}

C#速成
C#速成
C#速成
C#速成
C#速成
-------------------
C#速成装箱和拆箱操作(Boxing
/Unboxing)
C#速成
-------------------
C#速成
C#速成C#的装箱思想是全新的。上面提到过所有的数据类型,不论内置或用户自定义,全都从命名空间System的一个基类object派生出来。因此把基本的或者原始类型转换成object类型被称做装箱,反之,这种方式的逆操作被称为拆箱。
C#速成
C#速成示例:
C#速成
C#速成
class Test
{
C#速成   
static void Main()
{
C#速成      
int myInt = 12;
C#速成      
object obj = myInt ;       // 装箱
C#速成
      int myInt2 = (int) obj;    // 拆箱
C#速成
   }
C#速成}

C#速成
C#速成示例展示了装箱和拆箱操作。一个整型值转换成object类型,然后又转换回整型。当一个值类型的变量需要转换成引用类型时,一个object的箱子会被分配容纳这个值的空间,这个值会被复制进这个箱子。拆箱与此相反,一个object箱子中的数据被转换成它的原始值类型时,这个值将被从箱中复制到适当的存储位置。
英文原版:
C#速成
C#速成Environment: .NET, C#, Win XP, Win 
2000 
C#速成
C#速成Introduction
C#速成C# 
is a language with the features of C++, programming style like Java, and the rapid application model of Basic. If you already know the C++ language, it will take you less than an hour to quickly go through the syntax of C#. Familiarity with Java will be a plus because the Java program structure, the concept of packages, and garbage collection will definitely help you learn C# more quickly. So while discussing C# language constructs, I will assume that you know C++.
C#速成C#速成
C#速成(continued)
C#速成
C#速成
C#速成This article dicusses the C# language constructs and features, 
using code examples in a brief and comrehensive way so that you can, just by having a glance at the code, understand the concepts.
C#速成
C#速成Note: This article 
is not for C# gurus. There must be some other beginner's articles on C#, but this is yet another one.
C#速成

C#速成The following topics of the C# langauge are discussed:
C#速成
C#速成Program Structure 
C#速成Namespaces 
C#速成Data Types 
C#速成Variables 
C#速成Operators and Expressions 
C#速成Enumerations 
C#速成Statements 
C#速成Classes and Structs 
C#速成Modifiers 
C#速成Properties 
C#速成Interfaces 
C#速成Function Parameters 
C#速成Arrays 
C#速成Indexers 
C#速成Boxing and Unboxing 
C#速成Delegates 
C#速成Inheritance and Polymorphism 
C#速成The following topics are not discussed:
C#速成
C#速成Things that are common 
in C++ and C# 
C#速成Concepts such 
as garbage collection, threading, file processing, and so forth 
C#速成Data type conversions 
C#速成Exception handling 
C#速成.NET library 
C#速成Program Structure
C#速成Like C
++, C# is case-sensitive. The semicolon, ;, is the statement separator. Unlike C++, there are no separate declaration (header) and implementation(cpp) files in C#. All code (class declaration and implementation) is placed in one file with a cs extention.
C#速成
C#速成Have a look at 
this Hello world program in C#.
C#速成
C#速成
using System;
C#速成
C#速成
namespace MyNameSpace
C#速成
{
C#速成
C#速成
class HelloWorld
C#速成
{
C#速成    
static void Main(string[] args)
{
C#速成        Console.WriteLine (
"Hello World");
C#速成     }

C#速成}

C#速成
C#速成}

C#速成
C#速成Everything 
in C# is packed into a class and classes in C# are packed into namespaces (just like files in a folder). Like C++, a main method is the entry point of your program. C++'s main function is called "main", whereas C#'s main function starts with a capital M and is named "Main".
C#速成
C#速成There 
is no need to put a semicolon after a class block or struct definition. It was required in C++, but not in C#.
C#速成
C#速成Namespace
C#速成Every 
class is packaged into a namespace. Namespaces are exactly the same concept as in C++, but in C# we use namespaces more frequently than in C++. You can access a class in a namespace using dot . qualifier. MyNameSpace is the namespace in the hello world program above.
C#速成
C#速成Now, consider that you want to access the HelloWorld 
class from some other class in some other namespace.
C#速成
C#速成
using System;
C#速成
namespace AnotherNameSpace
{
C#速成    
class AnotherClass
{
C#速成        
public void Func()
{
C#速成            Console.WriteLine (
"Hello World");
C#速成        }

C#速成    }

C#速成}

C#速成
C#速成Now, from your HelloWorld 
class, you can access it as:
C#速成
C#速成
using System;
C#速成
using AnotherNameSpace;    // you will add this using statement
C#速成
namespace MyNameSpace
{
C#速成
class HelloWorld
{
C#速成    
static void Main(string[] args)
{
C#速成        AnotherClass obj 
= new AnotherClass();
C#速成        obj.Func();
C#速成    }

C#速成}

C#速成}

C#速成
C#速成In the .NET library, System 
is the top-level namespace in which other namespaces exist. By default, there exists a global namespace, so a class defined outside a namespace goes directly into this global namespace; hence, you can access this class without any qualifier.
C#速成
C#速成you can also define nested namespaces.
C#速成
C#速成Using
C#速成The #include directive 
is replaced with the "using" keyword, which is followed by a namespace name. Just as in "using System", above. "System" is the base-level namespace in which all other namespaces and classes are packed. The base class for all object is Object in the System namespace.
C#速成
C#速成Variables
C#速成Variables 
in C# are almost the same as in C++, except for these differences:
C#速成
C#速成Variables 
in C# (unlike C++) always need to be initialized before you access them; otherwise, you will get a compile time error. Hence, it's impossible to access an uninitialized variable. 
C#速成
You can't access a .dangling. pointer in C#. 
C#速成
An expression that indexes an array beyond its bounds is also not accessible. 
C#速成There are no global variables or functions 
in C# and the behavior of globals is acheived through static functions and static variables. 
C#速成Data Types
C#速成All types of C# are derived from a 
base-class object. There are two types of data types:
C#速成
C#速成Basic
/Built-in types 
C#速成User
-defined types 
C#速成Following 
is a table that lists built-in C# types:
C#速成
C#速成Type
C#速成 Bytes
C#速成 Desc
C#速成 
C#速成
byte 1 unsigned byte 
C#速成
sbyte 1 signed byte 
C#速成
short 2 signed short 
C#速成
ushort 2 unsigned short 
C#速成
int 4 signed integer 
C#速成
uint 4 unsigned integer 
C#速成
long 8 signed long 
C#速成
ulong 8 unsigned long 
C#速成
float 4 floating point number 
C#速成
double 8 double precision number 
C#速成
decimal 8 fixed precision number 
C#速成
string  unicode string 
C#速成
char  unicode char 
C#速成
bool truefalse boolean 
C#速成
C#速成Note: Type range 
in C# and C++ are different; for example, long in C++ is 4 bytes, and in C# it is 8 bytes. Also, the bool type and string types are different than those in C++. Bool accepts only true and false and not any integer.
C#速成User
-defined types include:
C#速成
C#速成Classes 
C#速成Structs 
C#速成Interfaces 
C#速成Memory allocation of the data types divides them into two types:
C#速成
C#速成Value Types 
C#速成Reference Types 
C#速成Value types
C#速成Value types are those data types that are allocated 
in the stack. They include:
C#速成
C#速成All basic or built
-in types except strings 
C#速成Structs 
C#速成Enum types 
C#速成Reference type
C#速成Reference types are allocated on the heap and are garbage collected when they are no longer being used. They are created 
using the new operator, and there is no delete operator for these types, unlike in C++, where the user has to explicitely delete the types created using the delete operator. In C#, they are automatically collected by the garbage collector.
C#速成
C#速成Reference types include:
C#速成
C#速成Classes 
C#速成Interfaces 
C#速成Collection types such 
as arrays 
C#速成String 
C#速成Enumeration
C#速成Enumerations 
in C# are exactly like C++. They are defined through a enum keyword.
C#速成
C#速成Example:
C#速成
C#速成
enum Weekdays
{
C#速成  Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
C#速成}

C#速成
C#速成Classes and Structs
C#速成Classes and structs are same 
as in C++, except in the difference of their memory allocation. Objects of classes are allocated in the heap, and are created using new, where as structs are allocated in the stack. Structs in C# are very light and fast datatypes. For heavy datatypes, you should create classes.
C#速成
C#速成Examples:
C#速成
C#速成
struct Date
{
C#速成    
int day;
C#速成    
int month;
C#速成    
int year;
C#速成}

C#速成
C#速成
class Date
{
C#速成    
int day;
C#速成    
int month;
C#速成    
int year;
C#速成    
string weekday;
C#速成    
string monthName;
C#速成    
public int GetDay()
{
C#速成        
return day;
C#速成    }

C#速成    
public int GetMonth()
{
C#速成        
return month;
C#速成    }

C#速成    
public int GetYear()
{
C#速成        
return year;
C#速成    }

C#速成    
public void SetDay(int Day)
{
C#速成        day 
= Day ;
C#速成    }

C#速成    
public void SetMonth(int Month)
{
C#速成        month 
= Month;
C#速成    }

C#速成    
public void SetYear(int Year)
{
C#速成        year 
= Year;
C#速成    }

C#速成    
public bool IsLeapYear()
{
C#速成        
return (year/4 == 0);
C#速成    }

C#速成    
public void SetDate (int day, int month, int year)
{
C#速成    }

C#速成    C#速成
C#速成}

C#速成
C#速成Properties
C#速成If you familiar with the 
object-oriented way of C++, you must have an idea of properties. Properties in the above example of the Date class are day, month, and year for which in C++, you write Get and Set methods. C# provides a more convinient, simple, and straightforward way of accessing properties.
C#速成
C#速成So, the above 
class can be written as:
C#速成
C#速成
using System;
C#速成
class Date
{
{
{
C#速成            
return day;
C#速成        }

{
C#速成            day 
= value;
C#速成        }

C#速成    }

C#速成    
int day;
C#速成
{
{
C#速成            
return month;
C#速成        }

{
C#速成            month 
= value;
C#速成        }

C#速成    }

C#速成    
int month;
C#速成
{
{
C#速成            
return year;
C#速成        }

{
C#速成            year 
= value;
C#速成        }

C#速成    }

C#速成    
int year;
C#速成
C#速成    
public bool IsLeapYear(int year)
{
C#速成        
return year%4== 0 ? truefalse;
C#速成    }

C#速成    
public void SetDate (int day, int month, int year)
{
C#速成        
this.day   = day;
C#速成        
this.month = month;
C#速成        
this.year  = year;
C#速成    }

C#速成}

C#速成
C#速成Here 
is the way you will get and set these properties:
C#速成
C#速成
class User
{
C#速成   
public static void Main()
{
C#速成        Date date 
= new Date();
C#速成        date.Day 
= 27;
C#速成        date.Month 
= 6;
C#速成        date.Year 
= 2003;
C#速成        Console.WriteLine(
"Date: {0}/{1}/{2}", date.Day,
C#速成                                               date.Month,
C#速成                                               date.Year);
C#速成    }

C#速成}

C#速成
C#速成Modifiers
C#速成You must be aware of 
publicprivate, and protected modifers that are commonly used in C++. Here, I will discuss some new modifiers introduced by C#.
C#速成
C#速成
readonly
C#速成The 
readonly modifier is used only for the class data members. As the name indicates, the readonly data members can only be read once they are written either directly initializing them or assigning values to them in constructor. The difference between the readonly and const data members is that const requires you to initialize with the declaration, that is directly. See this example code:
C#速成
C#速成
class MyClass
{
C#速成    
const int constInt = 100;    //directly
C#速成
    readonly int myInt = 5;      //directly
C#速成
    readonly int myInt2;
C#速成
C#速成    
public MyClass()
{
C#速成        myInt2 
= 8;              //Indirectly
C#速成
    }
C#速成    
public Func()
{
C#速成        myInt 
= 7;               //Illegal
C#速成
        Console.WriteLine(myInt2.ToString());
C#速成    }

C#速成
C#速成}

C#速成
C#速成
sealed
C#速成the 
sealed modifier with a class doesn't let you derive any class from it. So, you use this sealed keyword for the classes that you don't want to be inherited from.
C#速成
C#速成
sealed class CanNotbeTheParent
{
C#速成    
int a = 5;
C#速成}

C#速成
C#速成
unsafe
C#速成You can define an 
unsafe context in C# by using an unsafe modifier. In the unsafe context, you can write an unsafe code; for example, C++ pointers and so forth. See the following code:
C#速成
C#速成
public unsafe MyFunction( int * pInt, double* pDouble)
{
C#速成    
int* pAnotherInt = new int;
C#速成    
*pAnotherInt  = 10;
C#速成    pInt 
= pAnotherInt;
C#速成    C#速成
C#速成    
*pDouble = 8.9;
C#速成}

C#速成
C#速成Interfaces
C#速成If you have an idea of the COM, you will immediately know what I am talking about. An 
interface is the abstract base class containing only the function signatures whose implementation is provided by the child class. In C#, you define such classes as interfaces using the interface keyword. .NET is based on such interfaces. In C#, where you can't use multiple class inheritance, which was previously allowed in C++, the essence of multiple inheritance is acheived through interfaces. That's how your child class may implement multiple interfaces.
C#速成
C#速成
using System;
C#速成
interface myDrawing
{
C#速成    
int originx
{
C#速成        
get;
C#速成        
set;
C#速成    }

C#速成    
int originy
{
C#速成        
get;
C#速成        
set;
C#速成    }

C#速成    
void Draw(object shape);
C#速成}

C#速成
C#速成
class Shape: myDrawing
{
C#速成    
int OriX;
C#速成    
int OriY;
C#速成
C#速成    
public int originx
{
{
C#速成            
return OriX;
C#速成        }

{
C#速成            OriX 
= value;
C#速成        }

C#速成    }

C#速成    
public int originy
{
{
C#速成            
return OriY;
C#速成        }

{
C#速成            OriY 
= value;
C#速成        }

C#速成    }

C#速成    
public void Draw(object shape)
{
C#速成        C#速成    
// do something
C#速成
    }
C#速成
C#速成    
// class's own method
C#速成
    public void MoveShape(int newX, int newY)
{
C#速成    C#速成..
C#速成    }

C#速成
C#速成}

C#速成
C#速成Arrays
C#速成Arrays 
in C# are much better than in C++. Arrays are allocated in the heap and thus are of the reference type. You can't access an out-of-bound element in an array. So, C# prevents you from that type of bug. Also, some helper functions to iterate array elements are provided. foreach is the statement for such an iteration. The difference between the syntax of the C++ and C# array is:
C#速成

C#速成The square brackets are placed after the type and not after the variable name. 
C#速成You create element locations 
using new operator
C#速成C# supports single dimensional, multi dimensional, and jagged array (array of an array).
C#速成
C#速成Examples:
C#速成
C#速成    
int[] array = new int[10];              // single-dimensional
C#速成                                            
// array of int
C#速成
    for (int i = 0; i < array.Length; i++)
C#速成        array[i] 
= i;
C#速成
C#速成    
int[,] array2 = new int[5,10];          // 2-dimensional array
C#速成                                            
// of int
C#速成
    array2[1,2= 5;
C#速成
C#速成    
int[,,] array3 = new int[5,10,5];       // 3-dimensional array
C#速成                                            
// of int
C#速成
    array3[0,2,4= 9;
C#速成
C#速成    
int[][] arrayOfarray = = new int[2];    // Jagged array -
C#速成                                            
// array of array of
C#速成                                            
// int
C#速成
    arrayOfarray[0= new int[4];
;
C#速成
C#速成Indexers
C#速成An indexer 
is used to write a method to access an element from a collection using the straight way of using [], like an array. All you need is to specify the index to access an instance or element. The syntax of an indexer is same as that of class properties, except they take the input parameter, that is the index of the element.
C#速成
C#速成Example:
C#速成
C#速成Note: CollectionBase 
is the library class used for making collections. List is the protected member of CollectionBase, which stores the collection list.
C#速成
class Shapes: CollectionBase
{
C#速成    
public void add(Shape shp)
{
C#速成        List.Add(shp);
C#速成    }

C#速成
C#速成    
//indexer
C#速成
    public Shape this[int index]
{
{
C#速成            
return (Shape) List[index];
C#速成        }

{
C#速成            List[index] 
= value ;
C#速成         }

C#速成     }

C#速成}

C#速成
C#速成Boxing
/Unboxing
C#速成The idea of boxing 
is new in C#. As mentioned above, all data types, built-in or user defined, are derived from a base class object in the System namespace. So, the packing of basic or primitive types into an object is called boxing, whereas the reverse of this known as unboxing.
C#速成
C#速成Example:
C#速成
C#速成
class Test
{
C#速成   
static void Main()
{
C#速成      
int myInt = 12;
C#速成      
object obj = myInt ;       // boxing
C#速成
      int myInt2 = (int) obj;    // unboxing
C#速成
   }
C#速成}

C#速成
C#速成The example shows both boxing and unboxing. An 
int value can be converted to an object and back again to an int. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.
C#速成
C#速成Function Parameters
C#速成Parameters 
in C# are of three types:
C#速成
C#速成By
-Value/In parameters 
C#速成By
-Reference/In-Out parameters 
C#速成Out pParameters 
C#速成If you have an idea of the COM 
interface and its parameters types, you will easily understand the C# parameter types.
C#速成
C#速成By
-Value/In parameters
C#速成The concept of value parameters 
is the same as in C++. The value of the passed value is copied into a location and is passed to the function.
C#速成
C#速成Example:
C#速成
C#速成SetDay(
5);
C#速成C#速成
C#速成
void SetDay(int day)
{
C#速成    C#速成.
C#速成}

C#速成
C#速成By
-Reference/In-Out Parameters
C#速成The reference parameters 
in C++ are passed either through pointers or a reference operator&. In C#, reference parameters are less error prone. Reference parameters are also called In-Out parameters because you pass a reference address of the location, so you pass an input value and get an output value from that function.
C#速成
C#速成You cannot pass an uninitialized reference parameter into a function. C# uses a keyword 
ref for the reference parameters. You also have to use keyword ref with an argument while passing it to a function-demanding reference parameter.
C#速成
C#速成Example:
C#速成
C#速成    
int a= 5;
C#速成    FunctionA(
ref a);        // use ref with argument or you will
C#速成                             
// get a compiler error
C#速成
    Console.WriteLine(a);    // prints 20
C#速成

C#速成    
void FunctionA(ref int Val)
{
C#速成        
int x= Val;
C#速成        Val 
= x* 4;
C#速成    }

C#速成
C#速成Out parameter
C#速成The Out parameter 
is the parameter that only returns a value from the function. The input value is not required. C# uses the keyword out for the out parameters
C#速成
C#速成Example:
C#速成
C#速成    
int Val;
C#速成    GetNodeValue(Val);
C#速成
C#速成    
bool GetNodeValue(out int Val)
{
C#速成        Val 
= value;
C#速成        
return true;
C#速成    }

C#速成
C#速成Variable number of parameters and arrays
C#速成Arrays 
in C# are passed through a keyword params. An array-type parameter should always be the right-most argument of the function. Only one parameter can be of the array type. You can pass any number of elements as an argument of type of that array. You can better understand it from the following example.
C#速成
C#速成Example:
C#速成
C#速成    
void Func(params int[] array)
{
C#速成        Console.WriteLine(
"number of elements {0}",
C#速成                           array.Length);
C#速成    }

C#速成
C#速成    Func();                      
// prints 0
C#速成
    Func(5);                     // prints 1
C#速成
    Func(7,9);                   // prints 2

;
C#速成    Func(array);                 
// prints 8
C#速成

C#速成Operators and Expressions
C#速成Operators are exactly the same 
as om C++ and thus the expression, also. However, some new and useful operators have been added. Some of them are discussed here.
C#速成
C#速成
is operator
C#速成The 
is operator is used to check whether the operand types are equal or convertable. The is operator is particularly useful in the polymorphism scenarios. The is operator takes two operands and the result is a boolean. See the example:
C#速成
C#速成
void function(object param)
{
C#速成    
if(param is ClassA)
C#速成        
//do something
C#速成
    else if(param is MyStruct)
C#速成        
//do something
C#速成
    }
C#速成}
C#速成
C#速成
as operator
C#速成The 
as operator checks whether the type of the operands are convertable or equal (as is done by is operator) and if it is, the result is a converted or boxed object (if the operand can be boxed into the target type, see boxing/unboxing). If the objects are not convertable or boxable, the return is a null. Have a look at the example below to better understand the concept.
C#速成
C#速成Shape shp 
= new Shape();
C#速成Vehicle veh 
= shp as Vehicle;   // result is null, types are not
C#速成                                
// convertable
C#速成

C#速成Circle cir 
= new Circle();
C#速成Shape shp 
= cir;
C#速成Circle cir2 
= shp as Circle;    //will be converted
C#速成

C#速成
object[] objects = new object[2];
C#速成objects[
0= "Aisha";
C#速成
object[1= new Shape();
C#速成
C#速成
string str;
C#速成
for(int i=0; i&< objects.Length; i++)
{
C#速成    str 
= objects[i] as string;
C#速成    
if(str == null)
C#速成        Console.WriteLine(
"can not be converted");
C#速成    
else
C#速成        Console.WriteLine(
"{0}",str);
C#速成}

C#速成
C#速成Output:
C#速成Aisha
C#速成can not be converted
C#速成
C#速成Statements
C#速成Statements 
in C# are just like in C++ except some additions of new statements and modifications in some statements.
C#速成
C#速成The following are 
new statements:
C#速成
C#速成
foreach
C#速成For iteration of collections, such 
as arrays, and so forth.
C#速成
C#速成Example:
C#速成
C#速成    
foreach (string s in array)
C#速成        Console.WriteLine(s);
C#速成
C#速成
lock
C#速成Used 
in threads for locking a block of code, making it a critical section.
C#速成
C#速成
checked/unchecked
C#速成The statements are 
for overflow checking in numeric operations.
C#速成
C#速成Example:
C#速成
C#速成
int x = Int32.MaxValue; x++;    // Overflow checked
{
C#速成x
++;                            // Exception
C#速成
}
C#速成
unchecked
{
C#速成x
++;                            // Overflow}
C#速成
}
C#速成
C#速成The following statements are modified:
C#速成
C#速成Switch
C#速成The Switch statement 
is modified in C#.
C#速成
C#速成Now, after executing a 
case statement, program flow cannot jump to the next case, which was previously allowed in C++.
C#速成Example: 
C#速成
int var = 100;
C#速成
switch (var)
{
C#速成    
case 100: Console.WriteLine("<Value is 100>");
C#速成        
// No break here
C#速成
    case 200: Console.WriteLine("<Value is 200>"); break;
C#速成}

C#速成Output 
in C++:
C#速成    
<Value is 100><Value is 200>
C#速成
C#速成In C#, you 
get a compile time error:
C#速成
C#速成error CS0163: Control cannot fall through from one 
case label
C#速成(
'case 100:') to another
C#速成
C#速成However, you can 
do this similarly to the way you do it in C++
C#速成
switch (var)
{
C#速成    
case 100:
C#速成    
case 200: Console.WriteLine("100 or 200<VALUE is 200>");
C#速成              
break;
C#速成}

C#速成
C#速成You also can use constant variables 
for case values: 
C#速成Example:
C#速成
C#速成
const string WeekEnd  = "Sunday";
C#速成
const string WeekDay1 = "Monday";
C#速成
C#速成C#速成.
C#速成
C#速成
string WeekDay = Console.ReadLine();
C#速成
switch (WeekDay )
{
C#速成
case WeekEnd: Console.WriteLine("It's weekend!!"); break;
C#速成
case WeekDay1: Console.WriteLine("It's Monday"); break;
C#速成
C#速成}

C#速成
C#速成Delegates
C#速成Delegates let us store function references into a variable. In C
++this is like using and storing a function pointer for which we usually use typedef.
C#速成
C#速成Delegates are declared 
using a keyword delegate. Have a look at this example, and you will understand what delegates are:
C#速成
C#速成Example:
C#速成
C#速成
delegate int Operation(int val1, int val2);
C#速成
public int Add(int val1, int val2)
{
C#速成    
return val1 + val2;
C#速成}

C#速成
public int Subtract (int val1, int val2)
{
C#速成    
return val1- val2;
C#速成}

C#速成
C#速成
public void Perform()
{
C#速成    Operation Oper;
C#速成    Console.WriteLine(
"Enter + or - ");
C#速成    
string optor = Console.ReadLine();
C#速成    Console.WriteLine(
"Enter 2 operands");
C#速成
C#速成    
string opnd1 = Console.ReadLine();
C#速成    
string opnd2 = Console.ReadLine();
C#速成
C#速成    
int val1 = Convert.ToInt32 (opnd1);
C#速成    
int val2 = Convert.ToInt32 (opnd2);
C#速成
C#速成    
if (optor == "+")
C#速成        Oper 
= new Operation(Add);
C#速成    
else
C#速成        Oper 
= new Operation(Subtract);
C#速成
C#速成    Console.WriteLine(
" Result = {0}", Oper(val1, val2));
C#速成}

C#速成
C#速成Inheritance and Polymorphism
C#速成Only single inheritance 
is allowed in C#. Mutiple inheritance can be acheived by using interfaces.
C#速成
C#速成Example:
C#速成
{
C#速成}

C#速成
C#速成
class Child : Parent
C#速成
C#速成Virtual Functions
C#速成Virtual functions implement the concept of polymorphism are the same 
as in C#, except that you use the override keyword with the virtual function implementaion in the child class. The parent class uses the same virtual keyword. Every class that overrides the virtual method will use the override keyword.
C#速成
C#速成
class Shape
{
C#速成    
public virtual void Draw()
{
C#速成        Console.WriteLine(
"Shape.Draw")    ;
C#速成    }

C#速成}

C#速成
C#速成
class Rectangle : Shape
C#速成
{
C#速成    
public override void Draw()
{
C#速成        Console.WriteLine(
"Rectangle.Draw");
C#速成    }

C#速成}

C#速成
C#速成
class Square : Rectangle
{
C#速成    
public override void Draw()
{
C#速成        Console.WriteLine(
"Square.Draw");
C#速成    }

C#速成}

C#速成
class MainClass
{
C#速成    
static void Main(string[] args)
{
C#速成        Shape[] shp 
= new Shape[3];
C#速成        Rectangle rect 
= new Rectangle();
C#速成
C#速成        shp[
0= new Shape();
C#速成        shp[
1= rect;
C#速成        shp[
2= new Square();
C#速成
C#速成        shp[
0].Draw();
C#速成        shp[
1].Draw();
C#速成        shp[
2].Draw();
C#速成    }

C#速成}

C#速成Output:
C#速成Shape.Draw
C#速成Rectangle.Draw
C#速成Square.Draw
C#速成
C#速成Hiding parent functions 
using "new"
C#速成You can define 
in a child class a new version of a function, hiding the one which is in base class. A new keyword is used to define a new version. Consider the example below, which is a modified version of the above example and note the output this time, when I replace the override keyword with a new keyword in the Rectangle class.
C#速成
C#速成
class Shape
{
C#速成    
public virtual void Draw()
{
C#速成        Console.WriteLine(
"Shape.Draw")    ;
C#速成    }

C#速成}

C#速成
C#速成
class Rectangle : Shape
{
C#速成    
public new void Draw()
{
C#速成        Console.WriteLine(
"Rectangle.Draw");
C#速成    }

C#速成}

C#速成
class Square : Rectangle
{
C#速成    
//wouldn't let you override it here
C#速成
    public new void Draw()
{
C#速成        Console.WriteLine(
"Square.Draw");
C#速成    }

C#速成}

C#速成
class MainClass
{
C#速成    
static void Main(string[] args)
{
C#速成        Console.WriteLine(
"Using Polymorphism:");
C#速成        Shape[] shp 
= new Shape[3];
C#速成        Rectangle rect 
= new Rectangle();
C#速成
C#速成        shp[
0= new Shape();
C#速成        shp[
1= rect;
C#速成        shp[
2= new Square();
C#速成
C#速成        shp[
0].Draw();
C#速成        shp[
1].Draw();
C#速成        shp[
2].Draw();
C#速成
C#速成        Console.WriteLine(
"Using without Polymorphism:");
C#速成        rect.Draw();
C#速成        Square sqr 
= new Square();
C#速成        sqr.Draw();
C#速成    }

C#速成}

C#速成
C#速成Output:
C#速成Using Polymorphism
C#速成Shape.Draw
C#速成Shape.Draw
C#速成Shape.Draw
C#速成Using without Polymorphism:
C#速成Rectangle.Draw
C#速成Square.Draw
C#速成
C#速成The polymorphism doesn
't take the Rectangle class's Draw method as a polymorphic form of the Shape's Draw method. Instead, it considers it a different method. So, to avoid the naming conflict between parent and child, we have used the new modifier.
C#速成

C#速成Note: You cannot use the two version of a method 
in the same class, one with new modifier and other with override or virtual. As in the above example, I cannot add another method named Draw in the Rectangle class which is a virtual or override method. Also, in the Square class, I can't override the virtual Draw method of the Shape class.
C#速成
Calling base class members
C#速成If the child 
class has the data members with same name as that of base class, to avoid naming conflicts, base class data members and functions are accessed using a keyword base. See in the examples how the base class constructors are called and how the data members are used.
C#速成
C#速成
public Child(int val) :base(val)
{
C#速成    myVar 
= 5;
C#速成    
base.myVar;
C#速成}

C#速成
C#速成OR
C#速成
C#速成
public Child(int val)
{
C#速成    
base(val);
C#速成    myVar 
= 5 ;
C#速成    
base.myVar;
C#速成}

C#速成
C#速成Future Additions:
C#速成This article 
is just a quick overwiew of the C# language so that you can just become familiar with the langauge features. Although I have tried to discuss almost all the major concepts in C# in a brief and comprehensive way with code examples, I think there is lot much to be added and discussed.
C#速成
C#速成In the future, I would like to add more commands and concepts not yet discussed including events and so forth. I would also like to write about Windows programming 
using C# for beginners.
C#速成
C#速成References
C#速成our most commonly known MSDN 
C#速成Inside C# by Tom Archer 
C#速成A Programmer
's Introduction to C# by Eric Gunnerson 
C#速成
Beginning C# by Karli Watson 
C#速成Programming C# (O
'Reilly) 
C#速成
About the Author
C#速成Aisha 
is a Master of Science in Computer Science from Quaid-i-Azam Univeristy. She has worked in VC++ 6, MFC, ATL, COM/DCOM, ActiveX, C++, SQL, and so forth. These days she is working on .NET framework and C#. Inspired with nature, she loves to seek knowledge. She is also fond of travelling. She keeps a free source code and articles Web site at http://aishai.netfirms.com.

相关文章:

  • 2021-07-20
  • 2021-11-02
  • 2021-11-06
  • 2021-09-12
  • 2022-12-23
  • 2022-02-12
  • 2021-04-25
  • 2021-07-21
猜你喜欢
  • 2021-07-17
  • 2021-06-16
  • 2021-10-11
  • 2022-12-23
  • 2022-02-21
相关资源
相似解决方案