简介
C# 是一种具有 C++ 特性,Java 样式及 BASIC 快速建模特性的编程语言。
编程结构
C# 是大小写敏感的。半角分号(;)是语句分隔符。C# 中所有内容都打包在类中,而所有的类又打包在命名空间中(正如文件存与文件夹中)。和 C++ 一样,有一个主函数作为你程序的入口点。C++ 的主函数名为 main,而 C# 中是大写 M 打头的 Main。类块或结构定义之后没有必要再加一个半角分号。C++ 中是这样,但 C# 不要求。
命名空间
每个类都打包于一个命名空间。可以用点(.)定界符访问命名空间中的类。
Using:比如using System。System 是最基层的命名空间,所有其他命名空间和类都包含于其中。System 命名空间中所有对象的基类是 Object。
变量
1. C# 中(不同于 C++)的变量,总是需要你在访问它们前先进行初始化,否则你将遇到编译时错误。故而,不可能访问未初始化的变量。
2. 你不能在 C# 中访问一个“挂起”指针。
3. 超出数组边界的表达式索引值同样不可访问。
4. C# 中没有全局变量或全局函数,取而代之的是通过静态函数和静态变量完成的。
数据类型
所有 C# 的类型都是从 object 类继承的。有两种数据类型:1. 基本/内建类型 2. 用户定义类型
C# 内建类型的列表:
类型 字节 描述
byte 1 unsigned byte
sbyte 1 signed byte
short 2 signed short
ushort 2 unsigned short
int 4 signed integer
uint 4 unsigned integer
long 8 signed long
ulong 8 unsigned long
float 4 floating point number
double 8 double precision number
decimal 8 fixed precision number
string - Unicode string
char - Unicode char
bool true, false boolean
用户定义类型文件包含:
1. 类 (class)
2. 结构(struct)
3. 接口(interface)
注意:以下类型继承时均分配内存:1. 值类型 2. 参考类型。
值类型
值类型是在堆栈中分配的数据类型。它们包括了:
• 除字符串,所有基本和内建类型
• 结构
• 枚举类型
引用类型
引用类型在堆(heap)中分配内存且当其不再使用时,将自动进行垃圾清理。
引用类型包括:
• 类
• 接口
• 集合类型如数组
• 字符串
枚举
通过关键字 enum 定义。比如:
- enum Weekdays
- {
- Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
- }
类与结构
类的对象在堆中分配,并使用 new 关键字创建。而结构是在栈(stack)中进行分配。C# 中的结构属于轻量级快速数据类型。当需要大型数据类型时,你应该创建类。
- struct Date
- {
- int day;
- int month;
- int year;
- }
- class Date
- {
- int day;
- int month;
- int year;
- string weekday;
- string monthName;
- public int GetDay()
- {
- return day;
- }
- public int GetMonth()
- {
- return month;
- }
- public int GetYear()
- {
- return year;
- }
- public void SetDay(int Day)
- {
- day = Day ;
- }
- public void SetMonth(int Month)
- {
- month = Month;
- }
- public void SetYear(int Year)
- {
- year = Year;
- }
- public bool IsLeapYear()
- {
- return (year/4 == 0);
- }
- public void SetDate (int day, int month, int year)
- {
- }
- ...
- }
属性
C# 提供了一种更加便捷、简单而又直接的属性访问方式。上述代码改成:
- using System;
- class Date
- {
- public int Day{
- get {
- return day;
- }
- set {
- day = value;
- }
- }
- int day;
- public int Month{
- get {
- return month;
- }
- set {
- month = value;
- }
- }
- int month;
- public int Year{
- get {