读书笔记:W3CSchool学习教程-C#教程(上)

.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 Atkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012

String 类的属性

String 类有以下两个属性:

序号 属性名称 & 描述
1 Chars
在当前 String 对象中获取 Char 对象的指定位置。
2 Length
在当前的 String 对象中获取字符数。

String 类的方法

String 类有许多方法用于 string 对象的操作。下面的表格提供了一些最常用的方法:

序号 方法名称 & 描述
1 public static int Compare( string strA, string strB ) 
比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。
2 public static int Compare( string strA, string strB, bool ignoreCase ) 
比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。但是,如果布尔参数为真时,该方法不区分大小写。
3 public static string Concat( string str0, string str1 ) 
连接两个 string 对象。
4 public static string Concat( string str0, string str1, string str2 ) 
连接三个 string 对象。
5 public static string Concat( string str0, string str1, string str2, string str3 ) 
连接四个 string 对象。
6 public bool Contains( string value ) 
返回一个表示指定 string 对象是否出现在字符串中的值。
7 public static string Copy( string str ) 
创建一个与指定字符串具有相同值的新的 String 对象。
8 public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) 
从 string 对象的指定位置开始复制指定数量的字符到 Unicode 字符数组中的指定位置。
9 public bool EndsWith( string value ) 
判断 string 对象的结尾是否匹配指定的字符串。
10 public bool Equals( string value ) 
判断当前的 string 对象是否与指定的 string 对象具有相同的值。
11 public static bool Equals( string a, string b ) 
判断两个指定的 string 对象是否具有相同的值。
12 public static string Format( string format, Object arg0 ) 
把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。
13 public int IndexOf( char value ) 
返回指定 Unicode 字符在当前字符串中第一次出现的索引,索引从 0 开始。
14 public int IndexOf( string value ) 
返回指定字符串在该实例中第一次出现的索引,索引从 0 开始。
15 public int IndexOf( char value, int startIndex ) 
返回指定 Unicode 字符从该字符串中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
16 public int IndexOf( string value, int startIndex ) 
返回指定字符串从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
17 public int IndexOfAny( char[] anyOf ) 
返回某一个指定的 Unicode 字符数组中任意字符在该实例中第一次出现的索引,索引从 0 开始。
18 public int IndexOfAny( char[] anyOf, int startIndex ) 
返回某一个指定的 Unicode 字符数组中任意字符从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
19 public string Insert( int startIndex, string value ) 
返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置。
20 public static bool IsNullOrEmpty( string value ) 
指示指定的字符串是否为 null 或者是否为一个空的字符串。
21 public static string Join( string separator, params string[] value ) 
连接一个字符串数组中的所有元素,使用指定的分隔符分隔每个元素。
22 public static string Join( string separator, string[] value, int startIndex, int count ) 
链接一个字符串数组中的指定元素,使用指定的分隔符分隔每个元素。
23 public int LastIndexOf( char value ) 
返回指定 Unicode 字符在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
24 public int LastIndexOf( string value ) 
返回指定字符串在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
25 public string Remove( int startIndex ) 
移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。
26 public string Remove( int startIndex, int count ) 
从当前字符串的指定位置开始移除指定数量的字符,并返回字符串。
27 public string Replace( char oldChar, char newChar ) 
把当前 string 对象中,所有指定的 Unicode 字符替换为另一个指定的 Unicode 字符,并返回新的字符串。
28 public string Replace( string oldValue, string newValue ) 
把当前 string 对象中,所有指定的字符串替换为另一个指定的字符串,并返回新的字符串。
29 public string[] Split( params char[] separator ) 
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。
30 public string[] Split( char[] separator, int count ) 
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。int 参数指定要返回的子字符串的最大数目。
31 public bool StartsWith( string value ) 
判断字符串实例的开头是否匹配指定的字符串。
32 public char[] ToCharArray()
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。
33 public char[] ToCharArray( int startIndex, int length ) 
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组,从指定的索引开始,直到指定的长度为止。
34 public string ToLower()
把字符串转换为小写并返回。
35 public string ToUpper()
把字符串转换为大写并返回。
36 public 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 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

类 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 Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_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: 1
Friday: 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: 5
Printing float: 500.263
Printing 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 的体积: 210
Box2 的体积: 1560
Box3 的体积: 5400

可重载和不可重载运算符

下表描述了 C# 中运算符重载的能力:

运算符 描述
+, -, !, ~, ++, -- 这些一元运算符只有一个操作数,且可以被重载。
+, -, *, /, % 这些二元运算符带有两个操作数,且可以被重载。
==, !=, <, >, <=, >= 这些比较运算符可以被重载。
&&, || 这些条件逻辑运算符不能被直接重载。
+=, -=, *=, /=, %= 这些赋值运算符不能被重载。
=, ., ?:, ->, new, is, sizeof, typeof 这些运算符不能被重载。

实例

针对上述讨论,让我们扩展上面的实例,重载更多的运算符:

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 的体积: 210
Box2 的体积: 1560
Box3: (18, 20, 15)
Box3 的体积: 5400
Box1 不大于 Box2
Box1 小于 Box2
Box1 不大于等于 Box2
Box1 小于等于 Box2
Box1 不等于 Box2
Box3 等于 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 类的面积:
面积:70
Triangle 类的面积:
面积: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: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

C# 预处理器指令

预处理器指令指导编译器在实际编译开始之前对信息进行预处理。

所有的预处理器指令都是以 # 开始。且在一行上,只有空白字符可以出现在预处理器指令之前。预处理器指令不是语句,所以它们不以分号(;)结束。

C# 编译器没有一个单独的预处理器,但是,指令被处理时就像是有一个单独的预处理器一样。在 C# 中,预处理器指令用于在条件编译中起作用。与 C 和 C++ 不同指令不用,它们不是用来创建宏。一个预处理器指令必须是该行上的唯一指令。

C# 预处理器指令列表

下表列出了 C# 中可用的预处理器指令:

预处理器指令 描述
#define 它用于定义一系列成为符号的字符。
#undef 它用于取消定义符号。
#if 它用于测试符号是否为真。
#else 它用于创建复合条件指令,与 #if 一起使用。
#elif 它用于创建复合条件指令。
#endif 指定一个条件指令的结束。
#line 它可以让您修改编译器的行数以及(可选地)输出错误和警告的文件名。
#error 它允许从代码的指定位置生成一个错误。
#warning 它允许从代码的指定位置生成一级警告。
#region 它可以让您在使用 Visual Studio Code Editor 的大纲特性时,指定一个可展开或折叠的代码块。
#endregion 它标识着 #region 块的结束。

#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_V10
using 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 框架提供了允许这种匹配的正则表达式引擎。模式由一个或多个字符、运算符和结构组成。

定义正则表达式

下面列出了用于定义正则表达式的各种类别的字符、运算符和结构。

  • 字符转义
  • 字符类
  • 定位点
  • 分组构造
  • 限定符
  • 反向引用构造
  • 备用构造
  • 替换
  • 杂项构造

字符转义

正则表达式中的反斜杠字符(\)指示其后跟的字符是特殊字符,或应按原义解释该字符。

下表列出了转义字符:

转义字符 描述 模式 匹配
\a 与报警 (bell) 符 \u0007 匹配。 \a "Warning!" + '\u0007' 中的 "\u0007"
\b 在字符类中,与退格键 \u0008 匹配。 [\b]{3,} "\b\b\b\b" 中的 "\b\b\b\b"
\t 与制表符 \u0009 匹配。 (\w+)\t "Name\tAddr\t" 中的 "Name\t" 和 "Addr\t"
\r 与回车符 \u000D 匹配。(\r 与换行符 \n 不是等效的。) \r\n(\w+) "\r\Hello\nWorld." 中的 "\r\nHello"
\v 与垂直制表符 \u000B 匹配。 [\v]{2,} "\v\v\v" 中的 "\v\v\v"
\f 与换页符 \u000C 匹配。 [\f]{2,} "\f\f\f" 中的 "\f\f\f"
\n 与换行符 \u000A 匹配。 \r\n(\w+) "\r\Hello\nWorld." 中的 "\r\nHello"
\e 与转义符 \u001B 匹配。 \e "\x001B" 中的 "\x001B"
\ nnn 使用八进制表示形式指定一个字符(nnn 由二到三位数字组成)。 \w\040\w "a bc d" 中的 "a b" 和 "c d"
\x nn 使用十六进制表示形式指定字符(nn 恰好由两位数字组成)。 \w\x20\w "a bc d" 中的 "a b" 和 "c d"
\c X \c x 匹配 X 或 x 指定的 ASCII 控件字符,其中 X 或 x 是控件字符的字母。 \cC "\x0003" 中的 "\x0003" (Ctrl-C)
\u nnnn 使用十六进制表示形式匹配一个 Unicode 字符(由 nnnn 表示的四位数)。 \w\u0020\w "a bc d" 中的 "a b" 和 "c d"
\ 在后面带有不识别的转义字符时,与该字符匹配。 \d+[\+-x\*]\d+\d+[\+-x\*\d+ "(2+2) * 3*9" 中的 "2+2" 和 "3*9"

字符类

字符类与一组字符中的任何一个字符匹配。

下表列出了字符类:

字符类 描述 模式 匹配
[character_group] 匹配 character_group 中的任何单个字符。 默认情况下,匹配区分大小写。 [mn] "mat" 中的 "m","moon" 中的 "m" 和 "n"
[^character_group] 非:与不在 character_group 中的任何单个字符匹配。 默认情况下,character_group 中的字符区分大小写。 [^aei] "avail" 中的 "v" 和 "l"
[ first - last ] 字符范围:与从 first 到 last 的范围中的任何单个字符匹配。 (\w+)\t "Name\tAddr\t" 中的 "Name\t" 和 "Addr\t"
. 通配符:与除 \n 之外的任何单个字符匹配。 
若要匹配原意句点字符(. 或 \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"

定位点

定位点或原子零宽度断言会使匹配成功或失败,具体取决于字符串中的当前位置,但它们不会使引擎在字符串中前进或使用字符。

下表列出了定位点:

断言 描述 模式 匹配
^ 匹配必须从字符串或一行的开头开始。 ^\d{3} "567-777-" 中的 "567"
$ 匹配必须出现在字符串的末尾或出现在行或字符串末尾的 \n 之前。 -\d{4}$ "8-12-2012" 中的 "-2012"
\A 匹配必须出现在字符串的开头。 \A\w{3} "Code-007-" 中的 "Code"
\Z 匹配必须出现在字符串的末尾或出现在字符串末尾的\n 之前。 -\d{3}\Z "Bond-901-007" 中的 "-007"
\z 匹配必须出现在字符串的末尾。 -\d{3}\z "-901-333" 中的 "-333"
\G 匹配必须出现在上一个匹配结束的地方。 \\G\(\d\) "(1)(3)(5)[7](9)" 中的 "(1)"、 "(3)" 和 "(5)"
\b 匹配必须出现在 \w(字母数字)和 \W(非字母数字)字符之间的边界上。 \w "Room#1" 中的 "R"、 "o"、 "m" 和 "1"
\B 匹配不得出现在 \b 边界上。 \Bend\w*\b "end sends endure lender" 中的 "ends" 和 "ender"

分组构造

分组构造描述了正则表达式的子表达式,通常用于捕获输入字符串的子字符串。

下表列出了分组构造:

分组构造 描述 模式 匹配
( subexpression ) 捕获匹配的子表达式并将其分配到一个从零开始的序号中。 (\w)\1 "deep" 中的 "ee"
(?< name >subexpression) 将匹配的子表达式捕获到一个命名组中。 (?< double>\w)\k< double> "deep" 中的 "ee"
(?< name1 -name2 >subexpression) 定义平衡组定义。 (((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$ "3+2^((1-3)*(3-1))" 中的 "((1-3)*(3-1))"
(?: subexpression) 定义非捕获组。 Write(?:Line)? "Console.WriteLine()" 中的 "WriteLine"
(?imnsx-imnsx:subexpression) 应用或禁用 subexpression 中指定的选项。 A\d{2}(?i:\w+)\b "A12xl A12XL a12xl" 中的 "A12xl" 和 "A12XL"
(?= subexpression) 零宽度正预测先行断言。 \w+(?=\.) "He is. The dog ran. The sun is out." 中的 "is"、 "ran" 和 "out"
(?! subexpression) 零宽度负预测先行断言。 \b(?!un)\w+\b "unsure sure unity used" 中的 "sure" 和 "used"
(?< =subexpression) 零宽度正回顾后发断言。 (?< =19)\d{2}\b "1851 1999 1950 1905 2003" 中的 "51" 和 "03"
(?< ! subexpression) 零宽度负回顾后发断言。 (?< !19)\d{2}\b "end sends endure lender" 中的 "ends" 和 "ender"
(?> subexpression) 非回溯(也称为"贪婪")子表达式。 [13579](?>A+B+) "1ABB 3ABBC 5AB 5AC" 中的 "1ABB"、 "3ABB" 和 "5AB"

限定符

限定符指定在输入字符串中必须存在上一个元素(可以是字符、组或字符类)的多少个实例才能出现匹配项。 限定符包括下表中列出的语言元素。

下表列出了限定符:

限定符 描述 模式 匹配
* 匹配上一个元素零次或多次。 \d*\.\d ".0"、 "19.9"、 "219.9"
+ 匹配上一个元素一次或多次。 "be+" "been" 中的 "bee", "bent" 中的 "be"
? 匹配上一个元素零次或一次。 "rai?n" "ran"、 "rain"
{ n } 匹配上一个元素恰好 n 次。 ",\d{3}" "1,043.6" 中的 ",043", "9,876,543,210" 中的 ",876"、 ",543" 和 ",210"
{ n ,} 匹配上一个元素至少 n 次。 "\d{2,}" "166"、 "29"、 "1930"
{ n , m } 匹配上一个元素至少 n 次,但不多于 m 次。 "\d{3,5}" "166", "17668", "193024" 中的 "19302"
*? 匹配上一个元素零次或多次,但次数尽可能少。 \d*?\.\d ".0"、 "19.9"、 "219.9"
+? 匹配上一个元素一次或多次,但次数尽可能少。 "be+?" "been" 中的 "be", "bent" 中的 "be"
?? 匹配上一个元素零次或一次,但次数尽可能少。 "rai??n" "ran"、 "rain"
{ n }? 匹配前导元素恰好 n 次。 ",\d{3}?" "1,043.6" 中的 ",043", "9,876,543,210" 中的 ",876"、 ",543" 和 ",210"
{ n ,}? 匹配上一个元素至少 n 次,但次数尽可能少。 "\d{2,}?" "166"、 "29" 和 "1930"
{ n , m }? 匹配上一个元素的次数介于 n 和 m 之间,但次数尽可能少。 "\d{3,5}?" "166", "17668", "193024" 中的 "193" 和 "024"

反向引用构造

反向引用允许在同一正则表达式中随后标识以前匹配的子表达式。

下表列出了反向引用构造:

反向引用构造 描述 模式 匹配
\ number 反向引用。 匹配编号子表达式的值。 (\w)\1 "seek" 中的 "ee"
\k< name > 命名反向引用。 匹配命名表达式的值。 (?< char>\w)\k< char> "seek" 中的 "ee"

备用构造

备用构造用于修改正则表达式以启用 either/or 匹配。

下表列出了备用构造:

备用构造 描述 模式 匹配
| 匹配以竖线 (|) 字符分隔的任何一个元素。 th(e|is|at) "this is the day. " 中的 "the" 和 "this"
(?( expression )yes | no ) 如果正则表达式模式由 expression 匹配指定,则匹配 yes;否则匹配可选的 no部分。 expression 被解释为零宽度断言。 (?(A)A\d{2}\b|\b\d{3}\b) "A10 C103 910" 中的 "A10" 和 "910"
(?( name )yes | no ) 如果 name 或已命名或已编号的捕获组具有匹配,则匹配 yes;否则匹配可选的 no (?< quoted>")?(?(quoted).+?"|\S+\s) "Dogs.jpg "Yiska playing.jpg"" 中的 Dogs.jpg 和 "Yiska playing.jpg"

替换

替换是替换模式中使用的正则表达式。

下表列出了用于替换的字符:

字符 描述 模式 替换模式 输入字符串 结果字符串
$number 替换按组 number 匹配的子字符串。 \b(\w+)(\s)(\w+)\b $3$2$1 "one two" "two one"
${name} 替换按命名组 name 匹配的子字符串。 \b(?< word1>\w+)(\s)(?< word2>\w+)\b ${word2} ${word1} "one two" "two one"
$$ 替换字符"$"。 \b(\d+)\s?USD $$$1 "103 USD" "$103"
$& 替换整个匹配项的一个副本。 (\$*(\d*(\.+\d+)?){1}) **$& "$1.30" "**$1.30**"
$` 替换匹配前的输入字符串的所有文本。 B+ $` "AABBCC" "AAAACC"
$' 替换匹配后的输入字符串的所有文本。 B+ $' "AABBCC" "AACCCC"
$+ 替换最后捕获的组。 B+(C+) $+ "AABBCCDD" AACCDD
$_ 替换整个输入字符串。 B+ $_ "AABBCC" "AAAABBCCCC"

杂项构造

下表列出了各种杂项构造:

构造 描述 实例
(?imnsx-imnsx) 在模式中间对诸如不区分大小写这样的选项进行设置或禁用。 \bA(?i)b\w+\b 匹配 "ABA Able Act" 中的 "ABA" 和 "Able"
(?#comment) 内联注释。该注释在第一个右括号处终止。 \bA(?#Matches words starting with A)\w+\b
[to end of line] X 模式注释。 该注释以非转义的 # 开头,并继续到行的结尾。 (?x)\bA\w+\b#Matches words starting with A

Regex 类

Regex 类用于表示一个正则表达式。

下表列出了 Regex 类中一些常用的方法:

序号 方法 & 描述
1 public bool IsMatch( string input ) 
指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。
2 public bool IsMatch( string input, int startat ) 
指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项,从字符串中指定的开始位置开始。
3 public static bool IsMatch( string input, string pattern ) 
指示指定的正则表达式是否在指定的输入字符串中找到匹配项。
4 public MatchCollection Matches( string input ) 
在指定的输入字符串中搜索正则表达式的所有匹配项。
5 public string Replace( string input, string replacement ) 
在指定的输入字符串中,把所有匹配正则表达式模式的所有匹配的字符串替换为指定的替换字符串。
6 public 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*
Splendid
Suns

实例 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\b
make
maze
manage
measure

实例 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# 异常处理时建立在四个关键词之上的:trycatchfinally 和 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 类的预定义的异常类:

异常类 描述
System.IO.IOException 处理 I/O 错误。
System.IndexOutOfRangeException 处理当方法指向超出范围的数组索引时生成的错误。
System.ArrayTypeMismatchException 处理当数组类型不匹配时生成的错误。
System.NullReferenceException 处理当依从一个空对象时生成的错误。
System.DivideByZeroException 处理当除以零时生成的错误。
System.InvalidCastException 处理在类型转换期间生成的错误。
System.OutOfMemoryException 处理空闲内存不足生成的错误。
System.StackOverflowException 处理栈溢出生成的错误。

异常处理

C# 以 try 和 catch 块的形式提供了一种结构化的异常处理方案。使用这些块,把核心程序语句与错误处理语句分离开。

这些错误处理块是使用 trycatch 和 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 命名空间中常用的非抽象类:

I/O 类 描述
BinaryReader 从二进制流读取原始数据。
BinaryWriter 以二进制格式写入原始数据。
BufferedStream 字节流的临时存储。
Directory 有助于操作目录结构。
DirectoryInfo 用于对目录执行操作。
DriveInfo 提供驱动器的信息。
File 有助于处理文件。
FileInfo 用于对文件执行操作。
FileStream 用于文件中任何位置的读写。
MemoryStream 用于随机访问存储在内存中的数据流。
Path 对路径信息执行操作。
StreamReader 用于从字节流中读取字符。
StreamWriter 用于向一个流中写入字符。
StringReader 用于读取字符串缓冲区。
StringWriter 用于写入字符串缓冲区。

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 枚举定义了各种打开文件的方法。FileMode 枚举的成员有:

  • Append:打开一个已有的文件,并将光标放置在文件的末尾。如果文件不存在,则创建文件。
  • Create:创建一个新的文件。如果文件已存在,则删除旧文件,然后创建新文件。
  • CreateNew:指定操作系统应创建一个新的文件。如果文件已存在,则抛出异常。
  • Open:打开一个已有的文件。如果文件不存在,则抛出异常。
  • OpenOrCreate:指定操作系统应打开一个已有的文件。如果文件不存在,则用指定的名称创建一个新的文件打开。
  • Truncate:打开一个已有的文件,文件一旦打开,就将被截断为零字节大小。然后我们可以向文件写入全新的数据,但是保留文件的初始创建日期。如果文件不存在,则抛出异常。
FileAccess

FileAccess 枚举的成员有:ReadReadWrite 和 Write

FileShare

FileShare 枚举的成员有:

  • 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 类的强大功能,您需要知道这些类常用的属性和方法。

在下面的章节中,我们将讨论这些类和它们执行的操作。请单击链接详细了解各个部分的知识:

主题 描述
文本文件的读写 它涉及到文本文件的读写。StreamReader 和 StreamWriter 类有助于完成文本文件的读写。
二进制文件的读写 它涉及到二进制文件的读写。BinaryReader 和 BinaryWriter 类有助于完成二进制文件的读写。
Windows 文件系统的操作 它让 C# 程序员能够浏览并定位 Windows 文件和目录。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章