- 第1节:C# 简介
- 第2节:C# 环境
- 第3节:C# 程序结构
- 第4节:C# 基本语法
- 第5节:C# 数据类型
- 第6节:C# 类型转换
- 第7节:C# 变量
- 第8节:C# 常量
- 第9节:C# 运算符
- 第10节:C# 判断
- 第11节:C# 循环
- 第12节:C# 封装
- 第13节:C# 方法
- 第14节:C# 可空类型(Nullable)
- 第15节:C# 数组(Array)
- 第16节:C# 字符串(String)
- 第17节:C# 结构(Struct)
- 第18节:C# 枚举(Enum)
- 第19节:C# 类(Class)
- 第20节:C# 继承
- 第21节:C# 多态性
- 第22节:C# 运算符重载
- 第23节:C# 接口(Interface)
- 第24节:C# 命名空间(Namespace)
- 第25节:C# 预处理器指令
- 第26节:C# 正则表达式
- 第27节:C# 异常处理
- 第28节:C# 文件的输入与输出
- 第29节:C# 特性(Attribute)
- 第30节:C# 反射(Reflection)
- 第31节:C# 属性(Property)
- 第32节:C# 索引器(Indexer)
- 第33节:C# 委托(Delegate)
- 第34节:C# 事件(Event)
- 第35节:C# 集合(Collection)
- 第36节:C# 泛型(Generic)
- 第37节:C# 匿名方法
- 第38节:C# 不安全代码
- 第39节:C# 多线程
C# 基本语法
C# 是一种面向对象的编程语言。在面向对象的程序设计方法中,程序由各种相互交互的对象组成。相同种类的对象通常具有相同的类型,或者说,是在相同的 class 中。
例如,以 Rectangle(矩形)对象为例。它具有 length 和 width 属性。根据设计,它可能需要接受这些属性值、计算面积和显示细节。
让我们来看看一个 Rectangle(矩形)类的实现,并借此讨论 C# 的基本语法:
using System;
namespace RectangleApplication{
class Rectangle{
// 成员变量
double length;
double width;
public void Acceptdetails(){
length = 4.5;
width = 3.5;
}
public double GetArea(){
return length * width;
}
public void Display(){
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle{
static void Main(string[] args){
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
Length: 4.5
Width: 3.5
Area: 15.75
using 关键字
在任何 C# 程序中的第一条语句都是:
using System;
using 关键字用于在程序中包含命名空间。一个程序可以包含多个 using 语句。
class 关键字
class 关键字用于声明一个类。
C# 中的注释
注释是用于解释代码。编译器会忽略注释的条目。在 C# 程序中,多行注释以 /* 开始,并以字符 */ 终止,如下所示:
/* This program demonstrates
The basic syntax of C# programming
Language */
单行注释是用 '//' 符号表示。例如:
}//end class Rectangle
知识点补充:
C# 中 // 注释和 /// 注的区别:
C# 引入了新的 XML 注释,即我们在某个函数前新起一行,输入 ///,VS.Net 会自动增加 XML 格式的注释
// 不会被编译,而 /// 会被编译
所以使用 /// 会减慢编译的速度(但不会影响执行速度)
但使用 /// 会在其它的人调用你的代码时提供智能感知(通常在Form。Designer.cs 窗口会自动生成 /// 注释的程序)举个例子:
/// <summary>
/// 必需的设计器变量。 //定义属性,注意该属性为可读可写属性
/// </summary>
要注意必须有:
/// <summary>
///
/// </summary>
成员变量
变量是类的属性或数据成员,用于存储数据。在上面的程序中,Rectangle 类有两个成员变量,名为 length 和 width。
成员函数
函数是一系列执行指定任务的语句。类的成员函数是在类内声明的。我们举例的类 Rectangle 包含了三个成员函数: AcceptDetails
、GetArea
和 Display
。
实例化一个类
在上面的程序中,类 ExecuteRectangle 是一个包含 Main()
方法和实例化 Rectangle 类的类。
C# 类的实例化:通过已有的类(class)创建出该类的一个对象(object),这一过程就叫做类的实例化。
举个例子:你设计了一个汽车模型,交给工人师傅去加工制作,生产出一辆(一批)汽车。汽车模型就相当于程序中的类,生产出来的汽车就是对象,生产汽车这一过程就叫做类的实例化。
MyCar car1= new MyCar(); //类的实例化
标识符
标识符是用来识别类、变量、函数或任何其它用户定义的项目。在 C# 中,类的命名必须遵循如下基本规则:
- 标识符必须以字母开头,后面可以跟一系列的字母、数字( 0 - 9 )或下划线( _ )。标识符中的第一个字符不能是数字。
- 标识符必须不包含任何嵌入的空格或符号,比如 ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / \。但是,可以使用下划线( _ )。
- 标识符不能是 C# 关键字。
C# 关键字
关键字是 C# 编译器预定义的保留字。这些关键字不能用作标识符,但是,如果您想使用这些关键字作为标识符,可以在关键字前面加上 @ 字符作为前缀。
在 C# 中,有些标识符在代码的上下文中有特殊的意义,如 get 和 set,这些被称为上下文关键字(contextual keywords)。
下表列出了 C# 中的保留关键字(Reserved Keywords)和上下文关键字(Contextual Keywords):