读书笔记:W3CSchool学习教程-C#教程(上)
来源:互联网 发布:cmmb电视模块软件 编辑:程序博客网 时间:2024/05/29 19:43
.Net 框架(.Net Framework)
.Net 框架是一个创新的平台,能帮您编写出下面类型的应用程序:
- Windows 应用程序
- Web 应用程序
- Web 服务
.Net 框架由一个巨大的代码库组成,用于 C# 等客户端语言。下面列出一些 .Net 框架的组件:
- 公共语言运行库(Common Language Runtime - CLR)
- .Net 框架类库(.Net Framework Class Library)
- 公共语言规范(Common Language Specification)
- 通用类型系统(Common Type System)
- 元数据(Metadata)和组件(Assemblies)
- Windows 窗体(Windows Forms)
- ASP.Net 和 ASP.Net AJAX
- ADO.Net
- Windows 工作流基础(Windows Workflow Foundation - WF)
- Windows 显示基础(Windows Presentation Foundation)
- Windows 通信基础(Windows Communication Foundation - WCF)
- LINQ
C# 封装
抽象和封装是面向对象程序设计的相关特性。抽象允许相关信息可视化,封装则使程序员实现所需级别的抽象。
封装使用 访问修饰符 来实现。一个 访问修饰符 定义了一个类成员的范围和可见性。C# 支持的访问修饰符如下所示:
- Public
- Private
- Protected
- Internal
- Protected internal
C# 方法
<Access Specifier> <Return Type> <Method Name>(Parameter List){ Method Body}
using System;namespace CalculatorApplication{ class NumberManipulator { public int FindMax(int num1, int num2) { /* 局部变量声明 */ int result; if (num1 > num2) result = num1; else result = num2; return result; } } class Test { static void Main(string[] args) { /* 局部变量定义 */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //调用 FindMax 方法 ret = n.FindMax(a, b); Console.WriteLine("最大值是: {0}", ret ); Console.ReadLine(); } }}
按引用传递参数
引用参数是一个对变量的内存位置的引用。当按引用传递参数时,与值参数不同的是,它不会为这些参数创建一个新的存储位置。引用参数表示与提供给方法的实际参数具有相同的内存位置。
在 C# 中,使用 ref 关键字声明引用参数。
按输出传递参数
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(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
在方法调用之前,a 的值: 100在方法调用之后,a 的值: 5
提供给输出参数的变量不需要赋值。当需要从一个参数没有指定初始值的方法中返回值时,输出参数特别有用。请看下面的实例,来理解这一点:
using System;namespace CalculatorApplication{ class NumberManipulator { public void getValues(out int x, out int y ) { Console.WriteLine("请输入第一个值: "); x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("请输入第二个值: "); y = Convert.ToInt32(Console.ReadLine()); } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a , b; /* 调用函数来获取值 */ n.getValues(out a, out b); Console.WriteLine("在方法调用之后,a 的值: {0}", a); Console.WriteLine("在方法调用之后,b 的值: {0}", b); Console.ReadLine(); } }}
当上面的代码被编译和执行时,它会产生下列结果(取决于用户输入):
请输入第一个值:7请输入第二个值:8在方法调用之后,a 的值: 7在方法调用之后,b 的值: 8
C# 字符串(String)
在 C# 中,您可以使用字符数组来表示字符串,但是,更常见的做法是使用 string 关键字来声明一个字符串变量。string 关键字是 System.String 类的别名。
创建 String 对象
您可以使用以下方法之一来创建 string 对象:
- 通过给 String 变量指定一个字符串
- 通过使用 String 类构造函数
- 通过使用字符串串联运算符( + )
- 通过检索属性或调用一个返回字符串的方法
- 通过格式化方法来转换一个值或对象为它的字符串表示形式
下面的实例演示了这点:
using System;namespace StringApplication{ class Program { static void Main(string[] args) { //字符串,字符串连接 string fname, lname; fname = "Rowan"; lname = "Atkinson"; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //通过使用 string 构造函数 char[] letters = { 'H', 'e', 'l', 'l','o' }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //方法返回字符串 string[] sarray = { "Hello", "From", "Tutorials", "Point" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); //用于转化值的格式化方法 DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); Console.ReadKey() ; } }}
当上面的代码被编译和执行时,它会产生下列结果:
Full Name: Rowan AtkinsonGreetings: HelloMessage: Hello From Tutorials PointMessage: Message sent at 5:58 PM on Wednesday, October 10, 2012
String 类的属性
String 类有以下两个属性:
在当前 String 对象中获取 Char 对象的指定位置。2Length
在当前的 String 对象中获取字符数。
String 类的方法
String 类有许多方法用于 string 对象的操作。下面的表格提供了一些最常用的方法:
比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。2public static int Compare( string strA, string strB, bool ignoreCase )
比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。但是,如果布尔参数为真时,该方法不区分大小写。3public static string Concat( string str0, string str1 )
连接两个 string 对象。4public static string Concat( string str0, string str1, string str2 )
连接三个 string 对象。5public static string Concat( string str0, string str1, string str2, string str3 )
连接四个 string 对象。6public bool Contains( string value )
返回一个表示指定 string 对象是否出现在字符串中的值。7public static string Copy( string str )
创建一个与指定字符串具有相同值的新的 String 对象。8public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count )
从 string 对象的指定位置开始复制指定数量的字符到 Unicode 字符数组中的指定位置。9public bool EndsWith( string value )
判断 string 对象的结尾是否匹配指定的字符串。10public bool Equals( string value )
判断当前的 string 对象是否与指定的 string 对象具有相同的值。11public static bool Equals( string a, string b )
判断两个指定的 string 对象是否具有相同的值。12public static string Format( string format, Object arg0 )
把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。13public int IndexOf( char value )
返回指定 Unicode 字符在当前字符串中第一次出现的索引,索引从 0 开始。14public int IndexOf( string value )
返回指定字符串在该实例中第一次出现的索引,索引从 0 开始。15public int IndexOf( char value, int startIndex )
返回指定 Unicode 字符从该字符串中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。16public int IndexOf( string value, int startIndex )
返回指定字符串从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。17public int IndexOfAny( char[] anyOf )
返回某一个指定的 Unicode 字符数组中任意字符在该实例中第一次出现的索引,索引从 0 开始。18public int IndexOfAny( char[] anyOf, int startIndex )
返回某一个指定的 Unicode 字符数组中任意字符从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。19public string Insert( int startIndex, string value )
返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置。20public static bool IsNullOrEmpty( string value )
指示指定的字符串是否为 null 或者是否为一个空的字符串。21public static string Join( string separator, params string[] value )
连接一个字符串数组中的所有元素,使用指定的分隔符分隔每个元素。22public static string Join( string separator, string[] value, int startIndex, int count )
链接一个字符串数组中的指定元素,使用指定的分隔符分隔每个元素。23public int LastIndexOf( char value )
返回指定 Unicode 字符在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。24public int LastIndexOf( string value )
返回指定字符串在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。25public string Remove( int startIndex )
移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。26public string Remove( int startIndex, int count )
从当前字符串的指定位置开始移除指定数量的字符,并返回字符串。27public string Replace( char oldChar, char newChar )
把当前 string 对象中,所有指定的 Unicode 字符替换为另一个指定的 Unicode 字符,并返回新的字符串。28public string Replace( string oldValue, string newValue )
把当前 string 对象中,所有指定的字符串替换为另一个指定的字符串,并返回新的字符串。29public string[] Split( params char[] separator )
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。30public string[] Split( char[] separator, int count )
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。int 参数指定要返回的子字符串的最大数目。31public bool StartsWith( string value )
判断字符串实例的开头是否匹配指定的字符串。32public char[] ToCharArray()
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。33public char[] ToCharArray( int startIndex, int length )
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组,从指定的索引开始,直到指定的长度为止。34public string ToLower()
把字符串转换为小写并返回。35public string ToUpper()
把字符串转换为大写并返回。36public string Trim()
移除当前 String 对象中的所有前导空白字符和后置空白字符。
上面的方法列表并不详尽,请访问 MSDN 库,查看完整的方法列表和 String 类构造函数。
实例
下面的实例演示了上面提到的一些方法:
比较字符串
using System;namespace StringApplication{ class StringProg { static void Main(string[] args) { string str1 = "This is test"; string str2 = "This is text"; if (String.Compare(str1, str2) == 0) { Console.WriteLine(str1 + " and " + str2 + " are equal."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal."); } Console.ReadKey() ; } }}
当上面的代码被编译和执行时,它会产生下列结果:
This is test and This is text are not equal.
字符串包含字符串:
using System;namespace StringApplication{ class StringProg { static void Main(string[] args) { string str = "This is test"; if (str.Contains("test")) { Console.WriteLine("The sequence 'test' was found."); } Console.ReadKey() ; } }}
当上面的代码被编译和执行时,它会产生下列结果:
The sequence 'test' was found.
获取子字符串:
using System;namespace StringApplication{ class StringProg { static void Main(string[] args) { string str = "Last night I dreamt of San Pedro"; Console.WriteLine(str); string substr = str.Substring(23); Console.WriteLine(substr); } Console.ReadKey() ; }}
当上面的代码被编译和执行时,它会产生下列结果:
San Pedro
连接字符串:
using System;namespace StringApplication{ class StringProg { static void Main(string[] args) { string[] starray = new string[]{"Down the way nights are dark", "And the sun shines daily on the mountain top", "I took a trip on a sailing ship", "And when I reached Jamaica", "I made a stop"}; string str = String.Join("\n", starray); Console.WriteLine(str); } Console.ReadKey() ; }}
当上面的代码被编译和执行时,它会产生下列结果:
Down the way nights are darkAnd the sun shines daily on the mountain topI took a trip on a sailing shipAnd when I reached JamaicaI made a stop
类 vs 结构
类和结构有以下几个基本的不同点:
- 类是引用类型,结构是值类型。
- 结构不支持继承。
- 结构不能声明默认的构造函数。
针对上述讨论,让我们重写前面的实例:
using System; struct Books{ private string title; private string author; private string subject; private int book_id; public void getValues(string t, string a, string s, int id) { title = t; author = a; subject = s; book_id = id; } public void display() { Console.WriteLine("Title : {0}", title); Console.WriteLine("Author : {0}", author); Console.WriteLine("Subject : {0}", subject); Console.WriteLine("Book_id :{0}", book_id); }}; public class testStructure{ public static void Main(string[] args) { Books Book1 = new Books(); /* 声明 Book1,类型为 Book */ Books Book2 = new Books(); /* 声明 Book2,类型为 Book */ /* book 1 详述 */ Book1.getValues("C Programming", "Nuha Ali", "C Programming Tutorial",6495407); /* book 2 详述 */ Book2.getValues("Telecom Billing", "Zara Ali", "Telecom Billing Tutorial", 6495700); /* 打印 Book1 信息 */ Book1.display(); /* 打印 Book2 信息 */ Book2.display(); Console.ReadKey(); }}
当上面的代码被编译和执行时,它会产生下列结果:
Title : C ProgrammingAuthor : Nuha AliSubject : C Programming TutorialBook_id : 6495407Title : Telecom BillingAuthor : Zara AliSubject : Telecom Billing TutorialBook_id : 6495700
C# 枚举(Enum)
实例
下面的实例演示了枚举变量的用法:
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: 1Friday: 5
C# 多重继承
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(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
总面积: 35油漆总成本: $2450
C# 多态性
多态性意味着有多重形式。在面向对象编程范式中,多态性往往表现为"一个接口,多个功能"。
多态性可以是静态的或动态的。在静态多态性中,函数的响应是在编译时发生的。在动态多态性中,函数的响应是在运行时发生的。
静态多态性
在编译时,函数和对象的连接机制被称为早期绑定,也被称为静态绑定。C# 提供了两种技术来实现静态多态性。分别为:
- 函数重载
- 运算符重载
函数重载
您可以在同一个范围内对相同的函数名有多个定义。函数的定义必须彼此不同,可以是参数列表中的参数类型不同,也可以是参数个数不同。不能重载只有返回类型不同的函数声明。
下面的实例演示了几个相同的函数 print(),用于打印不同的数据类型:
using System;namespace PolymorphismApplication{ class Printdata { void print(int i) { Console.WriteLine("Printing int: {0}", i ); } void print(double f) { Console.WriteLine("Printing float: {0}" , f); } void print(string s) { Console.WriteLine("Printing string: {0}", s); } static void Main(string[] args) { Printdata p = new Printdata(); // 调用 print 来打印整数 p.print(5); // 调用 print 来打印浮点数 p.print(500.263); // 调用 print 来打印字符串 p.print("Hello C++"); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Printing int: 5Printing float: 500.263Printing string: Hello C++
C# 运算符重载
您可以重定义或重载 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;}
上面的函数为用户自定义的类 Box 实现了加法运算符(+)。它把两个 Box 对象的属性相加,并返回相加后的 Box 对象。
运算符重载的实现
下面的程序演示了完整的实现:
using System;namespace OperatorOvlApplication{ class Box { private double length; // 长度 private double breadth; // 宽度 private double height; // 高度 public double getVolume() { return length * breadth * height; } public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } // 重载 + 运算符来把两个 Box 对象相加 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; } } class Tester { static void Main(string[] args) { Box Box1 = new Box(); // 声明 Box1,类型为 Box Box Box2 = new Box(); // 声明 Box2,类型为 Box Box Box3 = new Box(); // 声明 Box3,类型为 Box double volume = 0.0; // 体积 // Box1 详述 Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // Box2 详述 Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // Box1 的体积 volume = Box1.getVolume(); Console.WriteLine("Box1 的体积: {0}", volume); // Box2 的体积 volume = Box2.getVolume(); Console.WriteLine("Box2 的体积: {0}", volume); // 把两个对象相加 Box3 = Box1 + Box2; // Box3 的体积 volume = Box3.getVolume(); Console.WriteLine("Box3 的体积: {0}", volume); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Box1 的体积: 210Box2 的体积: 1560Box3 的体积: 5400
可重载和不可重载运算符
下表描述了 C# 中运算符重载的能力:
实例
针对上述讨论,让我们扩展上面的实例,重载更多的运算符:
using System;namespace OperatorOvlApplication{ class Box { private double length; // 长度 private double breadth; // 宽度 private double height; // 高度 public double getVolume() { return length * breadth * height; } public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } // 重载 + 运算符来把两个 Box 对象相加 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; } public static bool operator == (Box lhs, Box rhs) { bool status = false; if (lhs.length == rhs.length && lhs.height == rhs.height && lhs.breadth == rhs.breadth) { status = true; } return status; } public static bool operator !=(Box lhs, Box rhs) { bool status = false; if (lhs.length != rhs.length || lhs.height != rhs.height || lhs.breadth != rhs.breadth) { status = true; } return status; } public static bool operator <(Box lhs, Box rhs) { bool status = false; if (lhs.length < rhs.length && lhs.height < rhs.height && lhs.breadth < rhs.breadth) { status = true; } return status; } public static bool operator >(Box lhs, Box rhs) { bool status = false; if (lhs.length > rhs.length && lhs.height > rhs.height && lhs.breadth > rhs.breadth) { status = true; } return status; } public static bool operator <=(Box lhs, Box rhs) { bool status = false; if (lhs.length <= rhs.length && lhs.height <= rhs.height && lhs.breadth <= rhs.breadth) { status = true; } return status; } public static bool operator >=(Box lhs, Box rhs) { bool status = false; if (lhs.length >= rhs.length && lhs.height >= rhs.height && lhs.breadth >= rhs.breadth) { status = true; } return status; } public override string ToString() { return String.Format("({0}, {1}, {2})", length, breadth, height); } } class Tester { static void Main(string[] args) { Box Box1 = new Box(); // 声明 Box1,类型为 Box Box Box2 = new Box(); // 声明 Box2,类型为 Box Box Box3 = new Box(); // 声明 Box3,类型为 Box Box Box4 = new Box(); double volume = 0.0; // 体积 // Box1 详述 Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // Box2 详述 Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // 使用重载的 ToString() 显示两个盒子 Console.WriteLine("Box1: {0}", Box1.ToString()); Console.WriteLine("Box2: {0}", Box2.ToString()); // Box1 的体积 volume = Box1.getVolume(); Console.WriteLine("Box1 的体积: {0}", volume); // Box2 的体积 volume = Box2.getVolume(); Console.WriteLine("Box2 的体积: {0}", volume); // 把两个对象相加 Box3 = Box1 + Box2; Console.WriteLine("Box3: {0}", Box3.ToString()); // Box3 的体积 volume = Box3.getVolume(); Console.WriteLine("Box3 的体积: {0}", volume); //comparing the boxes if (Box1 > Box2) Console.WriteLine("Box1 大于 Box2"); else Console.WriteLine("Box1 不大于 Box2"); if (Box1 < Box2) Console.WriteLine("Box1 小于 Box2"); else Console.WriteLine("Box1 不小于 Box2"); if (Box1 >= Box2) Console.WriteLine("Box1 大于等于 Box2"); else Console.WriteLine("Box1 不大于等于 Box2"); if (Box1 <= Box2) Console.WriteLine("Box1 小于等于 Box2"); else Console.WriteLine("Box1 不小于等于 Box2"); if (Box1 != Box2) Console.WriteLine("Box1 不等于 Box2"); else Console.WriteLine("Box1 等于 Box2"); Box4 = Box3; if (Box3 == Box4) Console.WriteLine("Box3 等于 Box4"); else Console.WriteLine("Box3 不等于 Box4"); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Box1: (6, 7, 5)Box2: (12, 13, 10)Box1 的体积: 210Box2 的体积: 1560Box3: (18, 20, 15)Box3 的体积: 5400Box1 不大于 Box2Box1 小于 Box2Box1 不大于等于 Box2Box1 小于等于 Box2Box1 不等于 Box2Box3 等于 Box4
动态多态性
C# 允许您使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。抽象类包含抽象方法,抽象方法可被派生类实现。派生类具有更专业的功能。
请注意,下面是有关抽象类的一些规则:
- 您不能创建一个抽象类的实例。
- 您不能在一个抽象类外部声明一个抽象方法。
- 通过在类定义前面放置关键字 sealed,可以将类声明为密封类。当一个类被声明为 sealed 时,它不能被继承。抽象类不能被声明为 sealed。
下面的程序演示了一个抽象类:
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(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Rectangle 类的面积:面积: 70
当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。虚方法是使用关键字 virtual 声明的。虚方法可以在不同的继承类中有不同的实现。对虚方法的调用是在运行时发生的。
动态多态性是通过 抽象类 和 虚方法 实现的。
下面的程序演示了这点:
using System;namespace PolymorphismApplication{ class Shape { protected int width, height; public Shape( int a=0, int b=0) { width = a; height = b; } public virtual int area() { Console.WriteLine("父类的面积:"); return 0; } } class Rectangle: Shape { public Rectangle( int a=0, int b=0): base(a, b) { } public override int area () { Console.WriteLine("Rectangle 类的面积:"); return (width * height); } } class Triangle: Shape { public Triangle(int a = 0, int b = 0): base(a, b) { } public override int area() { Console.WriteLine("Triangle 类的面积:"); return (width * height / 2); } } class Caller { public void CallArea(Shape sh) { int a; a = sh.area(); Console.WriteLine("面积: {0}", a); } } class Tester { static void Main(string[] args) { Caller c = new Caller(); Rectangle r = new Rectangle(10, 7); Triangle t = new Triangle(10, 5); c.CallArea(r); c.CallArea(t); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Rectangle 类的面积:面积:70Triangle 类的面积:面积:25
C# 接口(Interface)
接口定义了所有类继承接口时应遵循的语法合同。接口定义了语法合同 "是什么" 部分,派生类定义了语法合同 "怎么做" 部分。
接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。
抽象类在某种程度上与接口类似,但是,它们大多只是用在当只有少数方法由基类声明由派生类实现时。
声明接口
接口使用 interface 关键字声明,它与类的声明类似。接口声明默认是 public 的。下面是一个接口声明的实例:
public interface ITransactions{ // 接口成员 void showTransaction(); double getAmount();}
实例
下面的实例演示了上面接口的实现:
using System.Collections.Generic;using System.Linq;using System.Text;namespace InterfaceApplication{ public interface ITransactions { // 接口成员 void showTransaction(); double getAmount(); } public class Transaction : ITransactions { private string tCode; private string date; private double amount; public Transaction() { tCode = " "; date = " "; amount = 0.0; } public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; } public double getAmount() { return amount; } public void showTransaction() { Console.WriteLine("Transaction: {0}", tCode); Console.WriteLine("Date: {0}", date); Console.WriteLine("Amount: {0}", getAmount()); } } class Tester { static void Main(string[] args) { Transaction t1 = new Transaction("001", "8/10/2012", 78900.00); Transaction t2 = new Transaction("002", "9/10/2012", 451900.00); t1.showTransaction(); t2.showTransaction(); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Transaction: 001Date: 8/10/2012Amount: 78900Transaction: 002Date: 9/10/2012Amount: 451900
C# 预处理器指令
预处理器指令指导编译器在实际编译开始之前对信息进行预处理。
所有的预处理器指令都是以 # 开始。且在一行上,只有空白字符可以出现在预处理器指令之前。预处理器指令不是语句,所以它们不以分号(;)结束。
C# 编译器没有一个单独的预处理器,但是,指令被处理时就像是有一个单独的预处理器一样。在 C# 中,预处理器指令用于在条件编译中起作用。与 C 和 C++ 不同指令不用,它们不是用来创建宏。一个预处理器指令必须是该行上的唯一指令。
C# 预处理器指令列表
下表列出了 C# 中可用的预处理器指令:
#define 预处理器
#define 预处理器指令创建符号常量。
#define 允许您定义一个符号,这样,通过使用符号作为传递给 #if 指令的表达式,表达式将返回 true。它的语法如下:
#define symbol
下面的程序说明了这点:
#define PI using System;namespace PreprocessorDAppl{ class Program { static void Main(string[] args) { #if (PI) Console.WriteLine("PI is defined"); #else Console.WriteLine("PI is not defined"); #endif Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
PI is defined
条件指令
您可以使用 #if 指令来创建一个条件指令。条件指令用于测试符号是否为真。如果为真,编译器会执行 #if 和下一个指令之间的代码。
条件指令的语法:
#if symbol [operator symbol]...
其中,symbol 是要测试的符号名称。您也可以使用 true 和 false,或在符号前放置否定运算符。
运算符符号是用于评价符号的运算符。可以运算符可以是下列运算符之一:
- == (equality)
- != (inequality)
- && (and)
- || (or)
您也可以用括号把符号和运算符进行分组。条件指令用于在调试版本或编译指定配置时编译代码。一个以 #if 指令开始的条件指令,必须显示地以一个 #endif 指令终止。
下面的程序演示了条件指令的用法:
#define DEBUG#define VC_V10using System;public class TestClass{ public static void Main() { #if (DEBUG && !VC_V10) Console.WriteLine("DEBUG is defined"); #elif (!DEBUG && VC_V10) Console.WriteLine("VC_V10 is defined"); #elif (DEBUG && VC_V10) Console.WriteLine("DEBUG and VC_V10 are defined"); #else Console.WriteLine("DEBUG and VC_V10 are not defined"); #endif Console.ReadKey(); }}
当上面的代码被编译和执行时,它会产生下列结果:
DEBUG and VC_V10 are defined
C# 正则表达式
正则表达式 是一种匹配输入文本的模式。.Net 框架提供了允许这种匹配的正则表达式引擎。模式由一个或多个字符、运算符和结构组成。
定义正则表达式
下面列出了用于定义正则表达式的各种类别的字符、运算符和结构。
- 字符转义
- 字符类
- 定位点
- 分组构造
- 限定符
- 反向引用构造
- 备用构造
- 替换
- 杂项构造
字符转义
正则表达式中的反斜杠字符(\)指示其后跟的字符是特殊字符,或应按原义解释该字符。
下表列出了转义字符:
字符类
字符类与一组字符中的任何一个字符匹配。
下表列出了字符类:
若要匹配原意句点字符(. 或 \u002E),您必须在该字符前面加上转义符 (\.)。a.e"have" 中的 "ave", "mate" 中的 "ate"\p{ name }与 name 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。\p{Lu}"City Lights" 中的 "C" 和 "L"\P{ name }与不在 name 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。\P{Lu}"City" 中的 "i"、 "t" 和 "y"\w与任何单词字符匹配。\w"Room#1" 中的 "R"、 "o"、 "m" 和 "1"\W与任何非单词字符匹配。\W"Room#1" 中的 "#"\s与任何空白字符匹配。\w\s"ID A1.3" 中的 "D "\S与任何非空白字符匹配。\s\S"int __ctr" 中的 " _"\d与任何十进制数字匹配。\d"4 = IV" 中的 "4"\D匹配不是十进制数的任意字符。\D"4 = IV" 中的 " "、 "="、 " "、 "I" 和 "V"
定位点
定位点或原子零宽度断言会使匹配成功或失败,具体取决于字符串中的当前位置,但它们不会使引擎在字符串中前进或使用字符。
下表列出了定位点:
分组构造
分组构造描述了正则表达式的子表达式,通常用于捕获输入字符串的子字符串。
下表列出了分组构造:
限定符
限定符指定在输入字符串中必须存在上一个元素(可以是字符、组或字符类)的多少个实例才能出现匹配项。 限定符包括下表中列出的语言元素。
下表列出了限定符:
反向引用构造
反向引用允许在同一正则表达式中随后标识以前匹配的子表达式。
下表列出了反向引用构造:
备用构造
备用构造用于修改正则表达式以启用 either/or 匹配。
下表列出了备用构造:
替换
替换是替换模式中使用的正则表达式。
下表列出了用于替换的字符:
杂项构造
下表列出了各种杂项构造:
Regex 类
Regex 类用于表示一个正则表达式。
下表列出了 Regex 类中一些常用的方法:
指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。2public bool IsMatch( string input, int startat )
指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项,从字符串中指定的开始位置开始。3public static bool IsMatch( string input, string pattern )
指示指定的正则表达式是否在指定的输入字符串中找到匹配项。4public MatchCollection Matches( string input )
在指定的输入字符串中搜索正则表达式的所有匹配项。5public string Replace( string input, string replacement )
在指定的输入字符串中,把所有匹配正则表达式模式的所有匹配的字符串替换为指定的替换字符串。6public string[] Split( string input )
把输入字符串分割为子字符串数组,根据在 Regex 构造函数中指定的正则表达式模式定义的位置进行分割。
如需了解 Regex 类的完整的属性列表,请参阅微软的 C# 文档。
实例 1
下面的实例匹配了以 'S' 开头的单词:
using System;using System.Text.RegularExpressions;namespace RegExApplication{ class Program { private static void showMatch(string text, string expr) { Console.WriteLine("The Expression: " + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = "A Thousand Splendid Suns"; Console.WriteLine("Matching words that start with 'S': "); showMatch(str, @"\bS\S*"); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Matching words that start with 'S':The Expression: \bS\S*SplendidSuns
实例 2
下面的实例匹配了以 'm' 开头以 'e' 结尾的单词:
using System;using System.Text.RegularExpressions;namespace RegExApplication{ class Program { private static void showMatch(string text, string expr) { Console.WriteLine("The Expression: " + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = "make maze and manage to measure it"; Console.WriteLine("Matching words start with 'm' and ends with 'e':"); showMatch(str, @"\bm\S*e\b"); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Matching words start with 'm' and ends with 'e':The Expression: \bm\S*e\bmakemazemanagemeasure
实例 3
下面的实例替换掉多余的空格:
using System;using System.Text.RegularExpressions;namespace RegExApplication{ class Program { static void Main(string[] args) { string input = "Hello World "; string pattern = "\\s+"; string replacement = " "; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); Console.WriteLine("Original String: {0}", input); Console.WriteLine("Replacement String: {0}", result); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Original String: Hello World Replacement String: Hello World
C# 异常处理
异常是在程序执行期间出现的问题。C# 中的异常是对程序运行时出现的特殊情况的一种响应,比如尝试除以零。
异常提供了一种把程序控制权从某个部分转移到另一个部分的方式。C# 异常处理时建立在四个关键词之上的:try、catch、finally 和 throw。
- try:一个 try 块标识了一个将被激活的特定的异常的代码块。后跟一个或多个 catch 块。
- catch:程序通过异常处理程序捕获异常。catch 关键字表示异常的捕获。
- finally:finally 块用于执行给定的语句,不管异常是否被抛出都会执行。例如,如果您打开一个文件,不管是否出现异常文件都要被关闭。
- throw:当问题出现时,程序抛出一个异常。使用 throw 关键字来完成。
语法
假设一个块将出现异常,一个方法使用 try 和 catch 关键字捕获异常。try/catch 块内的代码为受保护的代码,使用 try/catch 语法如下所示:
try{ // 引起异常的语句}catch( ExceptionName e1 ){ // 错误处理代码}catch( ExceptionName e2 ){ // 错误处理代码}catch( ExceptionName eN ){ // 错误处理代码}finally{ // 要执行的语句}
您可以列出多个 catch 语句捕获不同类型的异常,以防 try 块在不同的情况下生成多个异常。
C# 中的异常类
C# 异常是使用类来表示的。C# 中的异常类主要是直接或间接地派生于 System.Exception 类。System.ApplicationException 和System.SystemException 类是派生于 System.Exception 类的异常类。
System.ApplicationException 类支持由应用程序生成的异常。所以程序员定义的异常都应派生自该类。
System.SystemException 类是所有预定义的系统异常的基类。
下表列出了一些派生自 Sytem.SystemException 类的预定义的异常类:
异常处理
C# 以 try 和 catch 块的形式提供了一种结构化的异常处理方案。使用这些块,把核心程序语句与错误处理语句分离开。
这些错误处理块是使用 try、catch 和 finally 关键字实现的。下面是一个当除以零时抛出异常的实例:
using System;namespace ErrorHandlingApplication{ class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
Exception caught: System.DivideByZeroException: Attempted to divide by zero. at ...Result: 0
创建用户自定义异常
您也可以定义自己的异常。用户自定义的异常类是派生自 ApplicationException 类。下面的实例演示了这点:
using System;namespace UserDefinedException{ class TestTemperature { static void Main(string[] args) { Temperature temp = new Temperature(); try { temp.showTemp(); } catch(TempIsZeroException e) { Console.WriteLine("TempIsZeroException: {0}", e.Message); } Console.ReadKey(); } }}public class TempIsZeroException: ApplicationException{ public TempIsZeroException(string message): base(message) { }}public class Temperature{ int temperature = 0; public void showTemp() { if(temperature == 0) { throw (new TempIsZeroException("Zero Temperature found")); } else { Console.WriteLine("Temperature: {0}", temperature); } }}
当上面的代码被编译和执行时,它会产生下列结果:
TempIsZeroException: Zero Temperature found
抛出对象
如果异常是直接或间接派生自 System.Exception 类,您可以抛出一个对象。您可以在 catch 块中使用 throw 语句来抛出当前的对象,如下所示:
Catch(Exception e){ ... Throw e}
C# 文件的输入与输出
一个 文件 是一个存储在磁盘中带有指定名称和目录路径的数据集合。当打开文件进行读写时,它变成一个 流。
从根本上说,流是通过通信路径传递的字节序列。有两个主要的流:输入流 和 输出流。输入流用于从文件读取数据(读操作),输出流用于向文件写入数据(写操作)。
C# I/O 类
System.IO 命名空间有各种不同的类,用于执行各种文件操作,如创建和删除文件、读取或写入文件,关闭文件等。
下表列出了一些 System.IO 命名空间中常用的非抽象类:
FileStream 类
System.IO 命名空间中的 FileStream 类有助于文件的读写与关闭。该类派生自抽象类 Stream。
您需要创建一个 FileStream 对象来创建一个新的文件,或打开一个已有的文件。创建 FileStream 对象的语法如下:
FileStream <object_name> = new FileStream( <file_name>,<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
例如,创建一个 FileStream 对象 F 来读取名为 sample.txt 的文件:
FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
FileMode 枚举定义了各种打开文件的方法。FileMode 枚举的成员有:
- Append:打开一个已有的文件,并将光标放置在文件的末尾。如果文件不存在,则创建文件。
- Create:创建一个新的文件。如果文件已存在,则删除旧文件,然后创建新文件。
- CreateNew:指定操作系统应创建一个新的文件。如果文件已存在,则抛出异常。
- Open:打开一个已有的文件。如果文件不存在,则抛出异常。
- OpenOrCreate:指定操作系统应打开一个已有的文件。如果文件不存在,则用指定的名称创建一个新的文件打开。
- Truncate:打开一个已有的文件,文件一旦打开,就将被截断为零字节大小。然后我们可以向文件写入全新的数据,但是保留文件的初始创建日期。如果文件不存在,则抛出异常。
FileAccess 枚举的成员有:Read、ReadWrite 和 Write。
FileShareFileShare 枚举的成员有:
- Inheritable:允许文件句柄可由子进程继承。Win32 不直接支持此功能。
- None:谢绝共享当前文件。文件关闭前,打开该文件的任何请求(由此进程或另一进程发出的请求)都将失败。
- Read:允许随后打开文件读取。如果未指定此标志,则文件关闭前,任何打开该文件以进行读取的请求(由此进程或另一进程发出的请求)都将失败。但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。
- ReadWrite:允许随后打开文件读取或写入。如果未指定此标志,则文件关闭前,任何打开该文件以进行读取或写入的请求(由此进程或另一进程发出)都将失败。但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。
- Write:允许随后打开文件写入。如果未指定此标志,则文件关闭前,任何打开该文件以进行写入的请求(由此进程或另一进过程发出的请求)都将失败。但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。
- Delete:允许随后删除文件。
实例
下面的程序演示了 FileStream 类的用法:
using System;using System.IO;namespace FileIOApplication{ class Program { static void Main(string[] args) { FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); for (int i = 1; i <= 20; i++) { F.WriteByte((byte)i); } F.Position = 0; for (int i = 0; i <= 20; i++) { Console.Write(F.ReadByte() + " "); } F.Close(); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
C# 高级文件操作
上面的实例演示了 C# 中简单的文件操作。但是,要充分利用 C# System.IO 类的强大功能,您需要知道这些类常用的属性和方法。
在下面的章节中,我们将讨论这些类和它们执行的操作。请单击链接详细了解各个部分的知识:
- 读书笔记:W3CSchool学习教程-C#教程(上)
- 读书笔记:W3CSchool学习教程-C#教程(下)
- w3cschool Java学习笔记 -Java教程
- w3cschool.cc SQLite 教程
- C# 教程读书笔记
- C# 教程读书笔记
- w3cschool教程 - jQuery插件总结
- w3cschool教程之jQuery UI 教程概述
- w3cschool菜鸟教程开通移动版本
- w3cschool的jQuery Mobile教程总结
- C# 学习教程之一
- C#学习教程五
- C#学习教程六
- C# 学习教程七
- C#学习教程八
- C# 学习教程九
- C#学习教程十一
- 《C#图解教程》 我的读书笔记
- 找第k大的东西(密码,uva 1262)
- 求两个整数的最大公约数和最小公倍数(通过调用自定义函数实现)
- 二叉树(C++实现)
- less is more
- apache (2.4.17)+tomcat(7.0.72)集群
- 读书笔记:W3CSchool学习教程-C#教程(上)
- pyschool_Lowest Common Multiple_t5_q13(最大公约数)
- DFU 中断不进入app的问题
- Spring的Quartz
- 电子商务秒杀所带来的问题?
- ORACLE AWR报告分析
- POJ 2115 C Looooops 拓展欧几里得
- iOS 对于下载请求超时重新下载的方法
- golang(Go语言) byte/[]byte 与 二进制形式字符串 互转