/* 我的第一个 C# 程序*/ Console.WriteLine("Hello World!"); Console.ReadKey();
编写 Console.Readkey(); 这个函数是为了在控制台窗口停留一下,直到敲击键盘为止。
不然运行时,"Hello World!" 这句话会在控制台窗口一闪而过,没法查看。
C# 简介
.Net 框架(.Net Framework)
.Net 框架是一个创新的平台,能帮您编写出下面类型的应用程序:
一个 C# 程序主要包括以下部分:
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(); } } }
成员变量
变量是类的属性或数据成员,用于存储数据。在上面的程序中,Rectangle 类有两个成员变量,名为 length 和 width。
成员函数
函数是一系列执行指定任务的语句。类的成员函数是在类内声明的。我们举例的类 Rectangle 包含了三个成员函数: AcceptDetails、GetArea 和 Display。
实例化一个类
在上面的程序中,类 ExecuteRectangle 是一个包含 Main() 方法和实例化 Rectangle 类的类。
C# 数据类型
在 C# 中,变量分为以下几种类型:
值类型(Value types)
值类型直接包含数据。比如 int、char、float,它们分别存储数字、字符、浮点数。当您声明一个 int 类型时,系统分配内存来存储值。
引用类型(Reference types)
内置的 引用类型有:object、dynamic 和 string。
当一个值类型转换为对象类型时,则被称为 装箱;另一方面,当一个对象类型转换为值类型时,则被称为 拆箱。
object obj; obj = 100; // 这是装箱
动态(Dynamic)类型
您可以存储任何类型的值在动态数据类型变量中。这些变量的类型检查是在运行时发生的。
dynamic= value; dynamic d = 20;
动态类型与对象类型相似,但是对象类型变量的类型检查是在编译时发生的,而动态类型变量的类型检查是在运行时发生的。
字符串(String)类型
字符串(String)类型的值可以通过两种形式进行分配:引号和 @引号。
String str = "runoob.com"; string str = @"C:\Windows";
指针类型(Pointer types)
指针类型变量存储另一种类型的内存地址
type* identifier; char* cptr; int* iptr;
C# 类型转换
C# 类型转换方法
C# 提供了下列内置的类型转换方法:
C# 变量
C# 中的变量定义
int i, j, k; char c, ch; float f, salary; double d;
接受来自用户的值
System 命名空间中的 Console 类提供了一个函数 ReadLine(),用于接收来自用户的输入,并把它存储到一个变量中。例如:
int num; num = Convert.ToInt32(Console.ReadLine());
函数 Convert.ToInt32() 把用户输入的数据转换为 int 数据类型,因为 Console.ReadLine() 只接受字符串格式的数据
C# 常量
整数常量
整数常量可以是十进制、八进制或十六进制的常量。前缀指定基数:0x 或 0X 表示十六进制,0 表示八进制,没有前缀则表示十进制。
整数常量也可以有后缀,可以是 U 和 L 的组合,其中,U 和 L 分别表示 unsigned 和 long。后缀可以是大写或者小写,多个后缀以任意顺序进行组合。
这里有一些整数常量的实例:
212 /* 合法 */ 215u /* 合法 */ 0xFeeL /* 合法 */ 078 /* 非法:8 不是一个八进制数字 */ 032UU /* 非法:不能重复后缀 */
85 /* 十进制 */ 0213 /* 八进制 */ 0x4b /* 十六进制 */ 30 /* int */ 30u /* 无符号 int */ 30l /* long */ 30ul /* 无符号 long */
浮点常量
一个浮点常量是由整数部分、小数点、小数部分和指数部分组成。您可以使用小数形式或者指数形式来表示浮点常量。
字符常量
字符常量是括在单引号里,例如,'x',且可存储在一个简单的字符类型变量中。一个字符常量可以是一个普通字符(例如 'x')、一个转义序列(例如 '\t')或者一个通用字符
C# 运算符
Console.WriteLine("c 的值是 {0}", c);
关系运算
逻辑运算符
位运算符
位运算符作用于位,并逐位执行操作。&、 | 和 ^ 的真值表如下所示:
赋值运算符
其他运算符
下表列出了 C# 支持的其他一些重要的运算符,包括 sizeof、typeof 和 ? :
C# 中的运算符优先级
C# 封装
C# 支持的访问修饰符如下所示:
C# 方法
要使用一个方法,您需要:
(Parameter List) { Method Body }
按引用传递参数
引用参数是一个对变量的内存位置的引用。当按引用传递参数时,与值参数不同的是,它不会为这些参数创建一个新的存储位置。引用参数表示与提供给方法的实际参数具有相同的内存位置。
在 C# 中,使用 ref 关键字声明引用参数。下面的实例演示了这点:
using System; namespace CalculatorApplication { class NumberManipulator { public void swap(ref int x, ref int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 temp 赋值给 y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int b = 200; Console.WriteLine("在交换之前,a 的值: {0}", a); Console.WriteLine("在交换之前,b 的值: {0}", b); /* 调用函数来交换值 */ n.swap(ref a, ref b); Console.WriteLine("在交换之后,a 的值: {0}", a); Console.WriteLine("在交换之后,b 的值: {0}", b); Console.ReadLine(); }
按输出传递参数
return 语句可用于只从函数中返回一个值。但是,可以使用 输出参数 来从函数中返回两个值。输出参数会把方法输出的数据赋给自己,其他方面与引用参数相似
using System; namespace CalculatorApplication { class NumberManipulator { public void getValue(out int x ) { int temp = 5; x = temp; } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; Console.WriteLine("在方法调用之前,a 的值: {0}", a); /* 调用函数来获取值 */ n.getValue(out a); Console.WriteLine("在方法调用之后,a 的值: {0}", a); Console.ReadLine(); } }
C# 可空类型(Nullable)
? : 单问号用于对 int,double,bool 等无法直接赋值为 null 的数据类型进行 null 的赋值,意思是这个数据类型是 NullAble 类型的。
int? i = 3 等同于 Nullablei = new Nullable (3); int i; //默认值0 int? ii; //默认值null
?? : 双问号 可用于判断一个变量在为 null 时返回一个指定的值。
Nullable< bool > 变量可以被赋值为 true 或 false 或 null。
< data_type> ?= null;
int? num1 = null; int? num2 = 45; double? num3 = new double?(); double? num4 = 3.14157; bool? boolval = new bool?(); // 显示值 Console.WriteLine("显示可空类型的值: {0}, {1}, {2}, {3}", num1, num2, num3, num4); Console.WriteLine("一个可空的布尔值: {0}", boolval); Console.ReadLine();
显示可空类型的值: , 45, , 3.14157 一个可空的布尔值:
Null 合并运算符( ?? )
如果第一个操作数的值为 null,则运算符返回第二个操作数的值,否则返回第一个操作数的值
using System; namespace CalculatorApplication { class NullablesAtShow { static void Main(string[] args) { double? num1 = null; double? num2 = 3.14157; double num3; num3 = num1 ?? 5.34; // num1 如果为空值则返回 5.34 Console.WriteLine("num3 的值: {0}", num3); num3 = num2 ?? 5.34; Console.WriteLine("num3 的值: {0}", num3); Console.ReadLine(); } } }
num3 的值: 5.34 num3 的值: 3.14157
C# 数组(Array)
datatype[] arrayName;
初始化数组
声明一个数组不会在内存中初始化数组。当初始化数组变量时,您可以赋值给数组。
数组是一个引用类型,所以您需要使用 new 关键字来创建数组的实例。
double[] balance = new double[10];
using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n 是一个带有 10 个整数的数组 */ int i,j; /* 初始化数组 n 中的元素 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } /* 输出每个数组元素的值 */ for (j = 0; j < 10; j++ ) { Console.WriteLine("Element[{0}] = {1}", j, n[j]); } Console.ReadKey(); } }
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
使用 foreach 循环
using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n 是一个带有 10 个整数的数组 */ /* 初始化数组 n 中的元素 */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* 输出每个数组元素的值 */ foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); } Console.ReadKey(); }
C# 多维数组
C# 支持多维数组。多维数组又称为矩形数组。
您可以声明一个 string 变量的二维数组,如下:
string [,] names;
或者,您可以声明一个 int 变量的三维数组,如下:
int [ , , ] m;
初始化二维数组
多维数组可以通过在括号内为每行指定值来进行初始化。下面是一个带有 3 行 4 列的数组。
int [,] a = new int [3,4] { {0, 1, 2, 3} , /* 初始化索引号为 0 的行 */ {4, 5, 6, 7} , /* 初始化索引号为 1 的行 */ {8, 9, 10, 11} /* 初始化索引号为 2 的行 */ };
C# 传递数组给函数
在 C# 中,您可以传递数组作为函数的参数
using System; namespace ArrayApplication { class MyArray { double getAverage(int[] arr, int size) { int i; double avg; int sum = 0; for (i = 0; i < size; ++i) { sum += arr[i]; } avg = (double)sum / size; return avg; } static void Main(string[] args) { MyArray app = new MyArray(); /* 一个带有 5 个元素的 int 数组 */ int [] balance = new int[]{1000, 2, 3, 17, 50}; double avg; /* 传递数组的指针作为参数 */ avg = app.getAverage(balance, 5 ) ; /* 输出返回值 */ Console.WriteLine( "平均值是: {0} ", avg ); Console.ReadKey(); }
C# 参数数组
参数数组通常用于传递未知数量的参数给函数。
C# 提供了 params 关键字,使调用数组为形参的方法时,既可以传递数组实参,也可以传递一组数组元素。params 的使用格式为:
public 返回类型 方法名称( params 类型名称[] 数组名称 ) using System; namespace ArrayApplication { class ParamArray { public int AddElements(params int[] arr) { int sum = 0; foreach (int i in arr) { sum += i; } return sum; } } class TestClass { static void Main(string[] args) { ParamArray app = new ParamArray(); int sum = app.AddElements(512, 720, 250, 567, 889); Console.WriteLine("总和是: {0}", sum); Console.ReadKey(); } }
C# Array 类
Array 类的属性
IsFixedSize
获取一个值,该值指示数组是否带有固定大小。
IsReadOnly
获取一个值,该值指示数组是否只读
Length
获取一个 32 位整数,该值表示所有维度的数组中的元素总数。
LongLength
获取一个 64 位整数,该值表示所有维度的数组中的元素总数。
Rank
获取数组的秩(维度)。
Array 类的方法
Clear
根据元素的类型,设置数组中某个范围的元素为零、为 false 或者为 null。
C# 结构体
定义结构体
为了定义一个结构体,您必须使用 struct 语句。struct 语句为程序定义了一个带有多个成员的新的数据类型。
例如,您可以按照如下的方式声明 Book 结构:
struct Books { public string title; public string author; public string subject; public int book_id; };
补充:类与结构体的区别
1、结构体中声明的字段无法赋予初值,类可以:
结构体的构造函数中,必须为结构体所有字段赋值
类的对象是存储在堆空间中,结构存储在栈中。堆空间大,但访问速度较慢,栈空间小,访问速度相对更快。故而,当我们描述一个轻量级对象的时候,结构可提高效率,成本更低。当然,这也得从需求出发,
C# 枚举(Enum)
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
C# 枚举是值类型
using System; namespace EnumApplication { class EnumProgram { enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat }; static void Main(string[] args) { int WeekdayStart = (int)Days.Mon; int WeekdayEnd = (int)Days.Fri; Console.WriteLine("Monday: {0}", WeekdayStart); Console.WriteLine("Friday: {0}", WeekdayEnd); Console.ReadKey(); } } }
Monday: 1 Friday: 5
C# 类(Class)
对象是类的实例。构成类的方法和变量成为类的成员。
类的默认访问标识符是 internal,成员的默认访问标识符是 private。
using System; namespace BoxApplication { class Box { public double length; // 长度 public double breadth; // 宽度 public double height; // 高度 } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // 声明 Box1,类型为 Box Box Box2 = new Box(); // 声明 Box2,类型为 Box double volume = 0.0; // 体积 // Box1 详述 Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; // Box2 详述 Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0; // Box1 的体积 volume = Box1.height * Box1.length * Box1.breadth; Console.WriteLine("Box1 的体积: {0}", volume); // Box2 的体积 volume = Box2.height * Box2.length * Box2.breadth; Console.WriteLine("Box2 的体积: {0}", volume); Console.ReadKey(); } }
C# 中的构造函数
类的 构造函数 是类的一个特殊的成员函数,当创建类的新对象时执行。
构造函数的名称与类的名称完全相同,它没有任何返回类型。
using System; namespace LineApplication { class Line { private double length; // 线条的长度 public Line() { Console.WriteLine("对象已创建"); } public void setLength( double len ) { length = len; } public double getLength() { return length; } static void Main(string[] args) { Line line = new Line(); // 设置线条长度 line.setLength(6.0); Console.WriteLine("线条的长度: {0}", line.getLength()); Console.ReadKey(); } }
C# 类的静态成员
关键字 static 意味着类中只有一个该成员的实例
using System; namespace StaticVarApplication { class StaticVar { public static int num; public void count() { num++; } public int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s1 = new StaticVar(); StaticVar s2 = new StaticVar(); s1.count(); s1.count(); s1.count(); s2.count(); s2.count(); s2.count(); Console.WriteLine("s1 的变量 num: {0}", s1.getNum()); Console.WriteLine("s2 的变量 num: {0}", s2.getNum()); Console.ReadKey(); } } } s1 的变量 num: 6 s2 的变量 num: 6
将类成员函数声明为public static无需实例化即可调用类成员函数
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { int num = AddClass.Add(2, 3); //编译通过 Console.WriteLine(num); } } class AddClass { public static int Add(int x,int y) { return x + y; } }
C# 继承
当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可。这个已有的类被称为的基类,这个新的类被称为派生类
基类和派生类
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。
假设,有一个基类 Shape,它的派生类是 Rectangle:
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // 派生类 class Rectangle: Shape { public int getArea() { return (width * height); } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // 打印对象的面积 Console.WriteLine("总面积: {0}", Rect.getArea()); Console.ReadKey(); } }
C# 不支持多重继承。但是,您可以使用接口来实现多重继承。
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // 基类 PaintCost public interface PaintCost { int getCost(int area); } // 派生类 class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // 打印对象的面积 Console.WriteLine("总面积: {0}", Rect.getArea()); Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area)); Console.ReadKey(); } }
C# 多态性
C# 提供了两种技术来实现静态多态性。分别为:
函数重载
您可以在同一个范围内对相同的函数名有多个定义。函数的定义必须彼此不同,可以是参数列表中的参数类型不同,也可以是参数个数不同。
动态多态性
C# 允许您使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。抽象类包含抽象方法,抽象方法可被派生类实现。派生类具有更专业的功能。
下面的程序演示了一个抽象类:
using System; namespace PolymorphismApplication { abstract class Shape { public abstract int area(); } class Rectangle: Shape { private int length; private int width; public Rectangle( int a=0, int b=0) { length = a; width = b; } public override int area () { Console.WriteLine("Rectangle 类的面积:"); return (width * length); } } class RectangleTester { static void Main(string[] args) { Rectangle r = new Rectangle(10, 7); double a = r.area(); Console.WriteLine("面积: {0}",a); Console.ReadKey(); } } }
当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。虚方法是使用关键字 virtual 声明的。虚方法可以在不同的继承类中有不同的实现。对虚方法的调用是在运行时发生的。
动态多态性是通过 抽象类 和 虚方法 实现的
继承类中的重写虚函数需要声明关键字 override
C# 运算符重载
operator 后跟运算符的符号来定义的
public static Box operator+ (Box b, Box c) { Box box = new Box(); box.length = b.length + c.length; box.breadth = b.breadth + c.breadth; box.height = b.height + c.height; return box; }
C# 接口(Interface)
接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。
接口使用 interface 关键字声明,它与类的声明类似。接口声明默认是 public 的。下面是一个接口声明的实例:
interface IMyInterface { void MethodToImplement(); }
以上代码定义了接口 IMyInterface。通常接口命令以 I 字母开头
接口继承: InterfaceInheritance.cs
以下实例定义了两个接口 IMyInterface 和 IParentInterface。
如果一个接口继承其他接口,那么实现类或结构就需要实现所有接口的成员。
以下实例 IMyInterface 继承了 IParentInterface 接口,因此接口实现类必须实现 MethodToImplement() 和 ParentInterfaceMethod() 方法:
using System; interface IParentInterface { void ParentInterfaceMethod(); } interface IMyInterface : IParentInterface { void MethodToImplement(); } class InterfaceImplementer : IMyInterface { static void Main() { InterfaceImplementer iImp = new InterfaceImplementer(); iImp.MethodToImplement(); iImp.ParentInterfaceMethod(); } public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); } public void ParentInterfaceMethod() { Console.WriteLine("ParentInterfaceMethod() called.");
C# 异常处理