2 C# 高级篇
特性
特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。
特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。.Net 框架提供了两种类型的特性:预定义特性和自定义特性。
列举特性
列举特性的语法如下:
- [attribute(positional_parameters, name_parameter = value, ...)]
- element
特性的名称和值都是在方括号内规定的,放在这个特性应用的元素之前。表示位置的参数规定出特性的基本信息,名称参数规定了可选择的信息。
预定义特性
.Net Framework 提供了三种预定义的特性:
- AttributeUsage
- Conditional
- Obsolete
AttributeUsage
该特性描述了用户定义的特性类是如何使用的。它规定了某个特性应用的项目类型。
规定这种特性的语法如下:
- [AttributeUsage(
- validon,
- AllowMultiple=allowmultiple,
- Inherited=inherited
- )]
其中,
- 参数 validon 规定特性了能承载特性的语言元素。它是枚举器 AttributeTargets 的值的组合。默认值是 AttributeTargets.All。
- 参数 allowmultiple(可选的)为该特性的 AllowMultiple 属性提供了一个布尔值。如果为 true,则该特性是多用的。默认值是 false(单用的)。
- 参数 inherited(可选的)为该特性的 Inherited 属性提供一个布尔值。如果为 true,则该特性可被派生类继承。默认值是 false(不可继承)。
例如:
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Constructor |
- AttributeTargets.Field |
- AttributeTargets.Method |
- AttributeTargets.Property,
- AllowMultiple = true)]
Conditional
这个预定义特性标记了一个条件方法,其执行依赖于特定的预处理标识符。
它会引起方法调用的条件编译,取决于指定的值,比如 Debug 或 Trace。例如,当调试代码时显示变量的值。
规定该特性的语法如下:
- [Conditional(
- conditionalSymbol
- )]
例如:
- [Conditional("DEBUG")]
下面的实例演示了该特性:
- #define DEBUG
- using System;
- using System.Diagnostics;
- public class Myclass
- {
- [Conditional("DEBUG")]
- public static void Message(string msg)
- {
- Console.WriteLine(msg);
- }
- }
- class Test
- {
- static void function1()
- {
- Myclass.Message("In Function 1.");
- function2();
- }
- static void function2()
- {
- Myclass.Message("In Function 2.");
- }
- public static void Main()
- {
- Myclass.Message("In Main function.");
- function1();
- Console.ReadKey();
- }
- }
编译执行上述代码,得到如下结果:
- In Main function
- In Function 1
- In Function 2
Obsolete
这个预定义特性标记了不应被使用的程序实体。它可以让您通知编译器丢弃某个特定的目标元素。例如,当一个新方法被用在一个类中,但是您仍然想要保持类中的旧方法,您可以通过显示一个应该使用新方法,而不是旧方法的消息,来把它标记为 obsolete(过时的)。
规定该特性的语法如下:
- [Obsolete(
- message
- )]
- [Obsolete(
- message,
- iserror
- )]
其中,
- 参数 message,是一个字符串,描述项目为什么过时的原因以及该替代使用什么。
- 参数 iserror,是一个布尔值。如果该值为 true,编译器应把该项目的使用当作一个错误。默认值是 false(编译器生成一个警告)。
下面的实例演示了该特性:
- using System;
- public class MyClass
- {
- [Obsolete("Don't use OldMethod, use NewMethod instead", true)]
- static void OldMethod()
- {
- Console.WriteLine("It is the old method");
- }
- static void NewMethod()
- {
- Console.WriteLine("It is the new method");
- }
- public static void Main()
- {
- OldMethod();
- }
- }
当你执行这个程序时,编译器会提示如下的错误:
- Don't use OldMethod, use NewMethod instead
创建自定义的特性
.Net 框架允许创建自定义特性,用于存储声明性的信息,且可在运行时被检索。该信息根据设计标准和应用程序需要,可与任何目标元素相关。
创建并使用自定义特性包含四个步骤:
- 声明自定义特性
- 构建自定义特性
- 在目标程序元素上应用自定义特性
- 通过反射访问特性
最后一个步骤包含编写一个简单的程序来读取元数据以便查找各种符号。元数据是用于描述其他数据的数据和信息。该程序应使用反射来在运行时访问特性。我们将在下一章详细讨论这点。
声明自定义特性
一个新的自定义特性应派生自 System.Attribute 类。例如:
- //一个自定义的特性BugFix被分配给类和类的成员
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Constructor |
- AttributeTargets.Field |
- AttributeTargets.Method |
- AttributeTargets.Property,
- AllowMultiple = true)]
- public class DeBugInfo : System.Attribute
在上面的代码中,我们已经声明了一个名为 DeBugInfo 的自定义特性。
构建自定义特性
让我们构建一个名为 DeBugInfo 的自定义特性,该特性将存储调试程序获得的信息。它存储下面的信息:
- bug 的代码编号
- 辨认该 bug 的开发人员名字
- 最后一次审查该代码的日期
- 一个存储了开发人员标记的字符串消息
我们的 DeBugInfo 类将带有三个用于存储前三个信息的私有属性(property)和一个用于存储消息的公有属性(property)。所以 bug 编号、开发人员名字和审查日期将是 DeBugInfo 类的必需的定位( positional)参数,消息将是一个可选的命名(named)参数。
每个特性必须至少有一个构造函数。必需的定位( positional)参数应通过构造函数传递。下面的代码演示了 DeBugInfo 类:
- //一个自定义的特性BugFix被分配给类和类的成员
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Constructor |
- AttributeTargets.Field |
- AttributeTargets.Method |
- AttributeTargets.Property,
- AllowMultiple = true)]
- public class DeBugInfo : System.Attribute
- {
- private int bugNo;
- private string developer;
- private string lastReview;
- public string message;
- public DeBugInfo(int bg, string dev, string d)
- {
- this.bugNo = bg;
- this.developer = dev;
- this.lastReview = d;
- }
- public int BugNo
- {
- get
- {
- return bugNo;
- }
- }
- public string Developer
- {
- get
- {
- return developer;
- }
- }
- public string LastReview
- {
- get
- {
- return lastReview;
- }
- }
- public string Message
- {
- get
- {
- return message;
- }
- set
- {
- message = value;
- }
- }
- }
应用自定义特性
通过将特性放置在目标之前来使用它:
- [DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
- [DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
- class Rectangle
- {
- //成员变量
- protected double length;
- protected double width;
- public Rectangle(double l, double w)
- {
- length = l;
- width = w;
- }
- [DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
- public double GetArea()
- {
- return length * width;
- }
- [DeBugInfo(56, "Zara Ali", "19/10/2012")]
- public void Display()
- {
- Console.WriteLine("Length: {0}", length);
- Console.WriteLine("Width: {0}", width);
- Console.WriteLine("Area: {0}", GetArea());
- }
- }
在下一章节中,我们会介绍如何使用 Reflection 类来检索特性信息。
反射
反射(Reflection) 对象用于在运行时获取类型信息。该类位于 System.Reflection 命名空间中,可访问一个正在运行的程序的元数据。
System.Reflection 命名空间包含了允许您获取有关应用程序信息及向应用程序动态添加类型、值和对象的类。
反射的应用
反射(Reflection)有下列用途:
- 它允许在运行时查看属性(attribute)信息。
- 它允许审查集合中的各种类型,以及实例化这些类型。
- 它允许延迟绑定的方法和属性(property)。
- 它允许在运行时创建新类型,然后使用这些类型执行一些任务。
查看元数据
我们已经在上面的章节中提到过,使用反射(Reflection)可以查看属性(attribute)信息。
System.Reflection 类的 MemberInfo 对象需要被初始化,用于发现与类相关的属性(attribute)。为了做到这点,您可以定义目标类的一个对象,如下:
- System.Reflection.MemberInfo info = typeof(MyClass);
下面的程序示范了这点:
- using System;
- [AttributeUsage(AttributeTargets.All)]
- public class HelpAttribute : System.Attribute
- {
- public readonly string Url;
- public string Topic // Topic 是一个表示名字的参数
- {
- get
- {
- return topic;
- }
- set
- {
- topic = value;
- }
- }
- public HelpAttribute(string url) // url 是一个表示位置的参数
- {
- this.Url = url;
- }
- private string topic;
- }
- [HelpAttribute("Information on the class MyClass")]
- class MyClass
- {
- }
- namespace AttributeAppl
- {
- class Program
- {
- static void Main(string[] args)
- {
- System.Reflection.MemberInfo info = typeof(MyClass);
- object[] attributes = info.GetCustomAttributes(true);
- for (int i = 0; i < attributes.Length; i++)
- {
- System.Console.WriteLine(attributes[i]);
- }
- Console.ReadKey();
- }
- }
- }
当上面的代码被编译和执行时,它会显示附加到类 MyClass 上的自定义属性:
- HelpAttribute
示例
在本实例中,我们将使用在上一章中创建的 DeBugInfo 属性,并使用反射(Reflection)来读取 Rectangle 类中的元数据。
- using System;
- using System.Reflection;
- namespace BugFixApplication
- {
- //自定义特性BugFix分配给一个类和他的成员
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Constructor |
- AttributeTargets.Field |
- AttributeTargets.Method |
- AttributeTargets.Property,
- AllowMultiple = true)]
- public class DeBugInfo : System.Attribute
- {
- private int bugNo;
- private string developer;
- private string lastReview;
- public string message;
- public DeBugInfo(int bg, string dev, string d)
- {
- this.bugNo = bg;
- this.developer = dev;
- this.lastReview = d;
- }
- public int BugNo
- {
- get
- {
- return bugNo;
- }
- }
- public string Developer
- {
- get
- {
- return developer;
- }
- }
- public string LastReview
- {
- get
- {
- return lastReview;
- }
- }
- public string Message
- {
- get
- {
- return message;
- }
- set
- {
- message = value;
- }
- }
- }
- [DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
- [DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
- class Rectangle
- {
- //成员变量
- protected double length;
- protected double width;
- public Rectangle(double l, double w)
- {
- length = l;
- width = w;
- }
- [DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
- public double GetArea()
- {
- return length * width;
- }
- [DeBugInfo(56, "Zara Ali", "19/10/2012")]
- public void Display()
- {
- Console.WriteLine("Length: {0}", length);
- Console.WriteLine("Width: {0}", width);
- Console.WriteLine("Area: {0}", GetArea());
- }
- }//Rectangle 类的结束
- class ExecuteRectangle
- {
- static void Main(string[] args)
- {
- Rectangle r = new Rectangle(4.5, 7.5);
- r.Display();
- Type type = typeof(Rectangle);
- //遍历 Rectangle 类的属性
- foreach (Object attributes in type.GetCustomAttributes(false))
- {
- DeBugInfo dbi = (DeBugInfo)attributes;
- if (null != dbi)
- {
- Console.WriteLine("Bug no: {0}", dbi.BugNo);
- Console.WriteLine("Developer: {0}", dbi.Developer);
- Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
- Console.WriteLine("Remarks: {0}", dbi.Message);
- }
- }
- //遍历方法属性
- foreach (MethodInfo m in type.GetMethods())
- {
- foreach (Attribute a in m.GetCustomAttributes(true))
- {
- DeBugInfo dbi = (DeBugInfo)a;
- if (null != dbi)
- {
- Console.WriteLine("Bug no: {0}, for Method: {1}", dbi.BugNo, m.Name);
- Console.WriteLine("Developer: {0}", dbi.Developer);
- Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
- Console.WriteLine("Remarks: {0}", dbi.Message);
- }
- }
- }
- Console.ReadLine();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Length: 4.5
- Width: 7.5
- Area: 33.75
- Bug No: 49
- Developer: Nuha Ali
- Last Reviewed: 10/10/2012
- Remarks: Unused variable
- Bug No: 45
- Developer: Zara Ali
- Last Reviewed: 12/8/2012
- Remarks: Return type mismatch
- Bug No: 55, for Method: GetArea
- Developer: Zara Ali
- Last Reviewed: 19/10/2012
- Remarks: Return type mismatch
- Bug No: 56, for Method: Display
- Developer: Zara Ali
- Last Reviewed: 19/10/2012
- Remarks:
属性
属性是类、结构体和接口的命名成员。类或结构体中的成员变量或方法称为域。属性是域的扩展,且可使用相同的语法来访问。它们使用访问器让私有域的值可被读写或操作。
属性不会确定存储位置。相反,它们具有可读写或计算它们值的访问器。
例如,有一个名为 Student 的类,带有 age、name 和 code 的私有域。我们不能在类的范围以外直接访问这些域,但是我们可以拥有访问这些私有域的属性。
访问器
属性的访问器包含有助于获取(读取或计算)或设置(写入)属性的可执行语句。访问器声明可包含一个 get 访问器、一个 set 访问器,或者同时包含二者。例如:
- // 为字符类型声明一个叫 Code 的属性:
- public string Code
- {
- get
- {
- return code;
- }
- set
- {
- code = value;
- }
- }
- // 为字符类型声明一个叫 Name 的属性:
- public string Name
- {
- get
- {
- return name;
- }
- set
- {
- name = value;
- }
- }
- // 为整形类型声明一个叫 Age 的属性:
- public int Age
- {
- get
- {
- return age;
- }
- set
- {
- age = value;
- }
- }
示例
下面的程序说明了特性是如何使用的:
- using System;
- namespace tutorialspoint
- {
- class Student
- {
- private string code = "N.A";
- private string name = "not known";
- private int age = 0;
- // 为字符类型声明一个叫 Code 的属性:
- public string Code
- {
- get
- {
- return code;
- }
- set
- {
- code = value;
- }
- }
- // 为字符类型声明一个叫 Name 的属性:
- public string Name
- {
- get
- {
- return name;
- }
- set
- {
- name = value;
- }
- }
- // 为整形类型声明一个叫 Age 的属性:
- public int Age
- {
- get
- {
- return age;
- }
- set
- {
- age = value;
- }
- }
- public override string ToString()
- {
- return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
- }
- }
- class ExampleDemo
- {
- public static void Main()
- {
- // 创建一个 Student 类的对象
- Student s = new Student();
- // 为 student 对象设置 code,name 和 age
- s.Code = "001";
- s.Name = "Zara";
- s.Age = 9;
- Console.WriteLine("Student Info: {0}", s);
- //为 age 加 1
- s.Age += 1;
- Console.WriteLine("Student Info: {0}", s);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Student Info: Code = 001, Name = Zara, Age = 9
- Student Info: Code = 001, Name = Zara, Age = 10
抽象属性
抽象类可拥有抽象属性,这些属性应在派生类中被实现。下面的程序说明了这点:
- using System;
- namespace tutorialspoint
- {
- public abstract class Person
- {
- public abstract string Name
- {
- get;
- set;
- }
- public abstract int Age
- {
- get;
- set;
- }
- }
- class Student : Person
- {
- private string code = "N.A";
- private string name = "N.A";
- private int age = 0;
- // 为字符类型声明一个叫 Code 的属性:
- public string Code
- {
- get
- {
- return code;
- }
- set
- {
- code = value;
- }
- }
- // 为字符类型声明一个叫 Name 的属性:
- public override string Name
- {
- get
- {
- return name;
- }
- set
- {
- name = value;
- }
- }
- // 为整形类型声明一个叫 Age 的属性:
- public override int Age
- {
- get
- {
- return age;
- }
- set
- {
- age = value;
- }
- }
- public override string ToString()
- {
- return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
- }
- }
- class ExampleDemo
- {
- public static void Main()
- {
- // 创建一个 Student 类的对象
- Student s = new Student();
- // 为 student 对象设置 code,name 和 age
- s.Code = "001";
- s.Name = "Zara";
- s.Age = 9;
- Console.WriteLine("Student Info:- {0}", s);
- //为age加1
- s.Age += 1;
- Console.WriteLine("Student Info:- {0}", s);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Student Info: Code = 001, Name = Zara, Age = 9
- Student Info: Code = 001, Name = Zara, Age = 10
索引器
创建索引器可以使一个对象像数组一样被索引。为类定义索引器时,该类的行为类似于一个虚拟数组,使用数组访问运算符([ ])则可以对该类来进行访问。
句法规则
创建一个一维索引器的规则如下:
- element-type this[int index]
- {
- // get 访问器
- get
- {
- // 返回 index 指定的值
- }
- // set 访问器
- set
- {
- // 设置 index 指定的值
- }
- }
使用索引器
索引器的声明在某种程度上类似于属性的声明,例如,使用 get 和 set 方法来定义一个索引器。不同的是,属性值的定义要求返回或设置一个特定的数据成员,而索引器的定义要求返回或设置的是某个对象实例的一个值,即索引器将实例数据切分成许多部分,然后通过一些方法去索引、获取或是设置每个部分。
定义属性需要提供属性名,而定义索引器需要提供一个指向对象实例的 this 关键字。
示例:
- using System;
- namespace IndexerApplication
- {
- class IndexedNames
- {
- private string[] namelist = new string[size];
- static public int size = 10;
- public IndexedNames()
- {
- for (int i = 0; i < size; i++)
- namelist[i] = "N. A.";
- }
- public string this[int index]
- {
- get
- {
- string tmp;
- if( index >= 0 && index <= size-1 )
- {
- tmp = namelist[index];
- }
- else
- {
- tmp = "";
- }
- return ( tmp );
- }
- set
- {
- if( index >= 0 && index <= size-1 )
- {
- namelist[index] = value;
- }
- }
- }
- static void Main(string[] args)
- {
- IndexedNames names = new IndexedNames();
- names[0] = "Zara";
- names[1] = "Riz";
- names[2] = "Nuha";
- names[3] = "Asif";
- names[4] = "Davinder";
- names[5] = "Sunil";
- names[6] = "Rubic";
- for ( int i = 0; i < IndexedNames.size; i++ )
- {
- Console.WriteLine(names[i]);
- }
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Zara
- Riz
- Nuha
- Asif
- Davinder
- Sunil
- Rubic
- N. A.
- N. A.
- N. A.
重载索引器
索引器允许重载,即允许使用多种不同类型的参数来声明索引器。索引值可以是整数,但也可以是其他的数据类型,如字符型。
重载索引器示例:
- using System;
- namespace IndexerApplication
- {
- class IndexedNames
- {
- private string[] namelist = new string[size];
- static public int size = 10;
- public IndexedNames()
- {
- for (int i = 0; i < size; i++)
- {
- namelist[i] = "N. A.";
- }
- }
- public string this[int index]
- {
- get
- {
- string tmp;
- if( index >= 0 && index <= size-1 )
- {
- tmp = namelist[index];
- }
- else
- {
- tmp = "";
- }
- return ( tmp );
- }
- set
- {
- if( index >= 0 && index <= size-1 )
- {
- namelist[index] = value;
- }
- }
- }
- public int this[string name]
- {
- get
- {
- int index = 0;
- while(index < size)
- {
- if (namelist[index] == name)
- {
- return index;
- }
- index++;
- }
- return index;
- }
- }
- static void Main(string[] args)
- {
- IndexedNames names = new IndexedNames();
- names[0] = "Zara";
- names[1] = "Riz";
- names[2] = "Nuha";
- names[3] = "Asif";
- names[4] = "Davinder";
- names[5] = "Sunil";
- names[6] = "Rubic";
- // 使用带有 int 参数的第一个索引器
- for (int i = 0; i < IndexedNames.size; i++)
- {
- Console.WriteLine(names[i]);
- }
- // 使用带有 string 参数的第二个索引器
- Console.WriteLine(names["Nuha"]);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Zara
- Riz
- Nuha
- Asif
- Davinder
- Sunil
- Rubic
- N. A.
- N. A.
- N. A.
- 2
委托
C# 中的委托类似于 C 或 C++ 中指向函数的指针。委托表示引用某个方法的引用类型变量,运行时可以更改引用对象。
特别地,委托可以用于处理事件或回调函数。并且,所有的委托类都是从 System.Delegate 类继承而来。
声明委托
声明委托时,需要定义能够被委托所引用的方法,任意委托可以引用与该委托拥有相同签名的方法。如:
- public delegate int MyDelegate (string s);
上述委托可以用于引用任何一个以字符型为参数的方法,且返回值类型为整型。
声明委托的句法规则为:
- delegate <return type> <delegate-name> <parameter list>
实例化委托
声明委托之后,必须使用 new 关键字和一个特定的方法来创建一个委托对象。创建时,传递到 new 语句的参数写法与方法调用相同,但是不带有参数,例如:
- public delegate void printString(string s);
- ...
- printString ps1 = new printString(WriteToScreen);
- printString ps2 = new printString(WriteToFile);
下述示例演示了委托的声明、实例化,此处的委托用于引用一个带有一个整型参数的方法,且该方法返回一个整型值。
- using System;
- delegate int NumberChanger(int n);
- namespace DelegateAppl
- {
- class TestDelegate
- {
- static int num = 10;
- public static int AddNum(int p)
- {
- num += p;
- return num;
- }
- public static int MultNum(int q)
- {
- num *= q;
- return num;
- }
- public static int getNum()
- {
- return num;
- }
- static void Main(string[] args)
- {
- // 创建委托实例
- NumberChanger nc1 = new NumberChanger(AddNum);
- NumberChanger nc2 = new NumberChanger(MultNum);
- // 使用委托对象调用方法
- nc1(25);
- Console.WriteLine("Value of Num: {0}", getNum());
- nc2(5);
- Console.WriteLine("Value of Num: {0}", getNum());
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Value of Num: 35
- Value of Num: 175
委托的多播
委托对象可通过 "+" 运算符进行合并。一个合并委托可以调用它所合并的两个委托,但只有相同类型的委托可被合并。"-" 运算符则可用于从合并的委托中移除其中一个委托。
利用委托的这种特性,可以创建一个委托被调用时所涉及的方法的调用列表。这被称为委托的多播,也叫组播。下面的程序演示了委托的多播:
- using System;
- delegate int NumberChanger(int n);
- namespace DelegateAppl
- {
- class TestDelegate
- {
- static int num = 10;
- public static int AddNum(int p)
- {
- num += p;
- return num;
- }
- public static int MultNum(int q)
- {
- num *= q;
- return num;
- }
- public static int getNum()
- {
- return num;
- }
- static void Main(string[] args)
- {
- // 创建委托实例
- NumberChanger nc;
- NumberChanger nc1 = new NumberChanger(AddNum);
- NumberChanger nc2 = new NumberChanger(MultNum);
- nc = nc1;
- nc += nc2;
- // 调用多播
- nc(5);
- Console.WriteLine("Value of Num: {0}", getNum());
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Value of Num: 75
委托的使用
下面的示例演示了委托的作用,示例中的 printString 委托可用于引用带有一个字符串作为输入的方法,且不返回数据。
我们使用这个委托来调用两个方法,第一个方法将字符串输出到控制台,第二个方法将字符串输出到文件:
- using System;
- using System.IO;
- namespace DelegateAppl
- {
- class PrintString
- {
- static FileStream fs;
- static StreamWriter sw;
- // 委托声明
- public delegate void printString(string s);
- // 该方法打印到控制台
- public static void WriteToScreen(string str)
- {
- Console.WriteLine("The String is: {0}", str);
- }
- // 该方法打印到文件
- public static void WriteToFile(string s)
- {
- fs = new FileStream("c:\\message.txt",
- FileMode.Append, FileAccess.Write);
- sw = new StreamWriter(fs);
- sw.WriteLine(s);
- sw.Flush();
- sw.Close();
- fs.Close();
- }
- // 该方法把委托作为参数,并使用它调用方法
- // call the methods as required
- public static void sendString(printString ps)
- {
- ps("Hello World");
- }
- static void Main(string[] args)
- {
- printString ps1 = new printString(WriteToScreen);
- printString ps2 = new printString(WriteToFile);
- sendString(ps1);
- sendString(ps2);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- The String is: Hello World
事件
事件指一个用户操作,如按键、点击、移动鼠标等,也可以是系统生成的通知。当事件发生时,应用需要对其作出相应的反应,如中断。另外,事件也用于内部进程通信。
通过事件使用委托
事件生成于类的声明中,通过使用同一个类或其他类中的委托与事件处理程序关联。包含事件的类用于发布事件,称为发布器类。其他接受该事件的类称为订阅器类。事件使用的是发布-订阅(publisher-subscriber)模型。
发布器是一个定义了事件和委托的对象,此外还定义了事件和委托之间的联系。一个发布器类的对象调用这个事件,同时通知其他的对象。
订阅器是一个接受事件并提供事件处理程序的对象。在发布器类中的委托调用订阅器类中的方法(或事件处理程序)。
声明事件
在类中声明一个事件,首先需要声明该事件对应的委托类型。如:
- public delegate void BoilerLogHandler(string status);
其次为使用 event 关键字来声明这个事件:
- //基于上述委托定义事件
- public event BoilerLogHandler BoilerEventLog;
上述代码段定义了一个名为 BoilerLogHandler 的委托以及一个名为 BoilerEventLog 的事件,该事件生成时会自动调用委托。
示例 1
- using System;
- namespace SimpleEvent
- {
- using System;
- public class EventTest
- {
- private int value;
- public delegate void NumManipulationHandler();
- public event NumManipulationHandler ChangeNum;
- protected virtual void OnNumChanged()
- {
- if (ChangeNum != null)
- {
- ChangeNum();
- }
- else
- {
- Console.WriteLine("Event fired!");
- }
- }
- public EventTest(int n )
- {
- SetValue(n);
- }
- public void SetValue(int n)
- {
- if (value != n)
- {
- value = n;
- OnNumChanged();
- }
- }
- }
- public class MainClass
- {
- public static void Main()
- {
- EventTest e = new EventTest(5);
- e.SetValue(7);
- e.SetValue(11);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Event Fired!
- Event Fired!
- Event Fired!
示例 2
该示例为一个简单的应用程序,该程序用于热水锅炉系统故障排除。当维修工程师检查锅炉时,锅炉的温度、压力以及工程师所写的备注都会被自动记录到一个日志文件中。
- using System;
- using System.IO;
- namespace BoilerEventAppl
- {
- // boiler 类
- class Boiler
- {
- private int temp;
- private int pressure;
- public Boiler(int t, int p)
- {
- temp = t;
- pressure = p;
- }
- public int getTemp()
- {
- return temp;
- }
- public int getPressure()
- {
- return pressure;
- }
- }
- // 事件发布器
- class DelegateBoilerEvent
- {
- public delegate void BoilerLogHandler(string status);
- // 基于上述委托定义事件
- public event BoilerLogHandler BoilerEventLog;
- public void LogProcess()
- {
- string remarks = "O. K";
- Boiler b = new Boiler(100, 12);
- int t = b.getTemp();
- int p = b.getPressure();
- if(t > 150 || t < 80 || p < 12 || p > 15)
- {
- remarks = "Need Maintenance";
- }
- OnBoilerEventLog("Logging Info:\n");
- OnBoilerEventLog("Temparature " + t + "\nPressure: " + p);
- OnBoilerEventLog("\nMessage: " + remarks);
- }
- protected void OnBoilerEventLog(string message)
- {
- if (BoilerEventLog != null)
- {
- BoilerEventLog(message);
- }
- }
- }
- // 该类保留写入日志文件的条款
- class BoilerInfoLogger
- {
- FileStream fs;
- StreamWriter sw;
- public BoilerInfoLogger(string filename)
- {
- fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
- sw = new StreamWriter(fs);
- }
- public void Logger(string info)
- {
- sw.WriteLine(info);
- }
- public void Close()
- {
- sw.Close();
- fs.Close();
- }
- }
- // 事件订阅器
- public class RecordBoilerInfo
- {
- static void Logger(string info)
- {
- Console.WriteLine(info);
- }//end of Logger
- static void Main(string[] args)
- {
- BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler.txt");
- DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();
- boilerEvent.BoilerEventLog += new
- DelegateBoilerEvent.BoilerLogHandler(Logger);
- boilerEvent.BoilerEventLog += new
- DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);
- boilerEvent.LogProcess();
- Console.ReadLine();
- filelog.Close();
- }//end of main
- }//end of RecordBoilerInfo
- }
编译执行上述代码,得到如下结果:
- Logging info:
- Temperature 100
- Pressure 12
- Message: O. K
集合
集合类专门用于数据存储和数据检索,并提供堆栈、队列、列表和哈希表的支持。目前,大多数集合类都实现了相同的接口。
集合类服务于不同的目的,如为元素动态分配内存,基于索引访问列表项等等,这些类所创建的是 Object 类的对象的集合。在 C# 中,Object 类是所有数据类型的基类。
各种集合类及其用法
下表为一些常用的以 System.Collection 为命名空间的集合类,点击相应链接,可查看详细说明。
类 | 描述及用法 |
---|---|
动态数组 | 动态数组表示可被单独索引的对象的有序集合。 动态数组基本上可以替代数组,但与数组不同的是,通过索引,动态数组可以在指定的位置添加和移除项目,且会自动重新调整大小,同样允许在列表中进行动态内存分配、增加、搜索、排序各项。 |
哈希表 | 哈希表使用键来访问集合中的元素。 当需要通过键访问元素时,则使用哈希表,且一个有用的键值可以很方便地被识别。哈希表中的每一项都有一个键/值对。键用于访问集合中的项目。 |
排序列表 | 排序列表使用键和索引来访问列表中的项。 它是数组和哈希表的组合,包含一个可使用键或索引访问各项的列表。若使用索引来访问各项,则它为一个动态数组,若使用键来访问各项,则它为一个哈希表。集合中的各项总是按键值排序。 |
堆栈 | 堆栈表示的是一个后进先出的对象集合。 当需要对各项进行后进先出的访问时,则使用堆栈。在列表中添加一项,称为推入元素;从列表中移除一项时,称为弹出元素。 |
队列 | 队列表示的是一个先进先出的对象集合。 当需要对各项进行先进先出的访问时,则使用队列。在列表中添加一项,称为入队;从列表中移除一项,称为出队。 |
点阵列 | 点阵列表示的是一个使用值 1 和 0 来表示的二进制数组。 当需要存储位,但事先不知道位数时,则使用点阵列。通过整型索引,可以从点阵列集合中访问各项,该索引值从零开始。 |
泛型
泛型允许推迟类或方法中编程元素的数据类型规范的编写,直到实际在程序中使用它的时候再编写。换句话说,泛型允许编写一个可以与任何数据类型协作的类或方法。
你可以通过数据类型的替代参数来编写类或方法的规范。当编译器遇到类的构造函数或方法的函数调用时,它会生成代码来处理指定的数据类型。下面这个简单的示例将有助于理解这个概念:
- using System;
- using System.Collections.Generic;
- namespace GenericApplication
- {
- public class MyGenericArray<T>
- {
- private T[] array;
- public MyGenericArray(int size)
- {
- array = new T[size + 1];
- }
- public T getItem(int index)
- {
- return array[index];
- }
- public void setItem(int index, T value)
- {
- array[index] = value;
- }
- }
- class Tester
- {
- static void Main(string[] args)
- {
- // 声明一个整型数组
- MyGenericArray<int> intArray = new MyGenericArray<int>(5);
- // 设置值
- for (int c = 0; c < 5; c++)
- {
- intArray.setItem(c, c*5);
- }
- // 获取值
- for (int c = 0; c < 5; c++)
- {
- Console.Write(intArray.getItem(c) + " ");
- }
- Console.WriteLine();
- // 声明一个字符数组
- MyGenericArray<char> charArray = new MyGenericArray<char>(5);
- // 设置值
- for (int c = 0; c < 5; c++)
- {
- charArray.setItem(c, (char)(c+97));
- }
- // 获取值
- for (int c = 0; c< 5; c++)
- {
- Console.Write(charArray.getItem(c) + " ");
- }
- Console.WriteLine();
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- 0 5 10 15 20
- a b c d e
泛型的特性
泛型是一种可以增强程序功能的技术,表现在如下几个方面:
- 它有助于最大限度地进行重用代码、确保类型的安全以及提高性能。
- 你可以创建泛型集合类。.NET 框架类库在 System.Collections.Generic 命名空间中包含了一些新的泛型集合类,你可以使用这些泛型集合类来替代 System.Collections 中的集合类。
- 你可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。
- 你可以对泛型类进行约束,使其只访问具有特定数据类型的方法。
- 在运行时,通过使用反射方法可以获取泛型数据类型中所使用的类型信息。
泛型方法
在之前的例子中,我们使用过一个泛型类,我们还可以通过类型参数来声明泛型方法。下述示例很好地展示了这个概念:
- using System;
- using System.Collections.Generic;
- namespace GenericMethodAppl
- {
- class Program
- {
- static void Swap<T>(ref T lhs, ref T rhs)
- {
- T temp;
- temp = lhs;
- lhs = rhs;
- rhs = temp;
- }
- static void Main(string[] args)
- {
- int a, b;
- char c, d;
- a = 10;
- b = 20;
- c = 'I';
- d = 'V';
- // 显示交换之前的值
- Console.WriteLine("Int values before calling swap:");
- Console.WriteLine("a = {0}, b = {1}", a, b);
- Console.WriteLine("Char values before calling swap:");
- Console.WriteLine("c = {0}, d = {1}", c, d);
- // 调用 swap 进行交换
- Swap<int>(ref a, ref b);
- Swap<char>(ref c, ref d);
- // 显示交换之后的值
- Console.WriteLine("Int values after calling swap:");
- Console.WriteLine("a = {0}, b = {1}", a, b);
- Console.WriteLine("Char values after calling swap:");
- Console.WriteLine("c = {0}, d = {1}", c, d);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Int values before calling swap:
- a = 10, b = 20
- Char values before calling swap:
- c = I, d = V
- Int values after calling swap:
- a = 20, b = 10
- Char values after calling swap:
- c = V, d = I
泛型委托
你可以通过类型参数来定义一个泛型委托,如:
- delegate T NumberChanger<T>(T n);
泛型委托示例:
- using System;
- using System.Collections.Generic;
- delegate T NumberChanger<T>(T n);
- namespace GenericDelegateAppl
- {
- class TestDelegate
- {
- static int num = 10;
- public static int AddNum(int p)
- {
- num += p;
- return num;
- }
- public static int MultNum(int q)
- {
- num *= q;
- return num;
- }
- public static int getNum()
- {
- return num;
- }
- static void Main(string[] args)
- {
- // 创建委托实例
- NumberChanger<int> nc1 = new NumberChanger<int>(AddNum);
- NumberChanger<int> nc2 = new NumberChanger<int>(MultNum);
- // 使用委托对象调用方法
- nc1(25);
- Console.WriteLine("Value of Num: {0}", getNum());
- nc2(5);
- Console.WriteLine("Value of Num: {0}", getNum());
- Console.ReadKey();
- }
- }
- }
编译执行以上代码,得到如下结果:
- Value of Num: 35
- Value of Num: 175
匿名方法
先前的章节中提过,委托是用于引用与其具有相同签名的方法,即使用委托对象,就可以调用任何被该委托引用的方法。
匿名方法提供了一种将一段代码块作为委托参数的技术。顾名思义,匿名方法没有名字,只有方法主体。
你不需要为匿名方法指定返回类型,其返回类型直接由方法主体推断而来。
编写匿名方法
匿名方法通过使用 delegate 关键字创建委托实例来实现方法的声明,如:
- delegate void NumberChanger(int n);
- ...
- NumberChanger nc = delegate(int x)
- {
- Console.WriteLine("Anonymous Method: {0}", x);
- };
上述代码块中的 Console.WriteLine("Anonymous Method: {0}", x); 就是匿名方法的主体。
委托可以通过匿名方法调用,也可以通过命名方法调用,即,通过向委托对象来传递方法参数,如:
- nc(10);
示例
- using System;
- delegate void NumberChanger(int n);
- namespace DelegateAppl
- {
- class TestDelegate
- {
- static int num = 10;
- public static void AddNum(int p)
- {
- num += p;
- Console.WriteLine("Named Method: {0}", num);
- }
- public static void MultNum(int q)
- {
- num *= q;
- Console.WriteLine("Named Method: {0}", num);
- }
- public static int getNum()
- {
- return num;
- }
- static void Main(string[] args)
- {
- //使用匿名方法创建委托实例
- NumberChanger nc = delegate(int x)
- {
- Console.WriteLine("Anonymous Method: {0}", x);
- };
- //使用匿名方法调用委托
- nc(10);
- //使用命名方法实例化委托
- nc = new NumberChanger(AddNum);
- //使用命名方法调用委托
- nc(5);
- //使用另一个命名方法实例化委托
- nc = new NumberChanger(MultNum);
- //使用另一个命名方法调用委托
- nc(2);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Anonymous Method: 10
- Named Method: 15
- Named Method: 30
不安全代码
当代码段被 unsafe 修饰符标记时,C# 允许该代码段中的函数使用指针变量,故使用了指针变量的代码块又被称为不安全代码或非托管代码。
注意: 若要在 codingground 中执行本章的程序,请将 Project >> Compile Options >> Compilation Command to 中的编辑项设置为 mcs *.cs -out:main.exe -unsafe"
指针
指针是指其值为另一个变量的地址的变量,即内存位置的直接地址。如一般的变量或常量一样,在使用指针来存储其他变量的地址之前,必须先进行指针声明。
声明指针变量的一般形式为:
- type *var-name;
以下为一些有效的指针声明示例:
- int *ip; /* pointer to an integer */
- double *dp; /* pointer to a double */
- float *fp; /* pointer to a float */
- char *ch /* pointer to a character */
下述示例为在 C# 中使用了 unsafe 修饰符时指针的使用:
- using System;
- namespace UnsafeCodeApplication
- {
- class Program
- {
- static unsafe void Main(string[] args)
- {
- int var = 20;
- int* p = &var;
- Console.WriteLine("Data is: {0} ", var);
- Console.WriteLine("Address is: {0}", (int)p);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Data is: 20
- Address is: 99215364
除了将整个方法声明为不安全代码之外,还可以只将部分代码声明为不安全代码,下面章节中的的示例说明了这点。
使用指针检索数据值
使用 ToString() 方法可以检索存储在指针变量所引用位置的数据。例如:
- using System;
- namespace UnsafeCodeApplication
- {
- class Program
- {
- public static void Main()
- {
- unsafe
- {
- int var = 20;
- int* p = &var;
- Console.WriteLine("Data is: {0} " , var);
- Console.WriteLine("Data is: {0} " , p->ToString());
- Console.WriteLine("Address is: {0} " , (int)p);
- }
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果
- Data is: 20
- Data is: 20
- Address is: 77128984
传递指针作为方法的参数
指针可以作为方法中的参数,例如:
- using System;
- namespace UnsafeCodeApplication
- {
- class TestPointer
- {
- public unsafe void swap(int* p, int *q)
- {
- int temp = *p;
- *p = *q;
- *q = temp;
- }
- public unsafe static void Main()
- {
- TestPointer p = new TestPointer();
- int var1 = 10;
- int var2 = 20;
- int* x = &var1;
- int* y = &var2;
- Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2);
- p.swap(x, y);
- Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Before Swap: var1: 10, var2: 20
- After Swap: var1: 20, var2: 10
使用指针访问数组元素
在 C# 中,数组名称与一个指向与数组数据具有相同数据类型的指针是不同的变量类型。例如 int *p 和 int[] 是不同的类型。你可以对指针变量 p 进行加操作,因为它在内存中是不固定的,反之,数组的地址在内存中是固定的,因而无法对其直接进行加操作。
故如同 C 或 C++,这里同样需要使用一个指针变量来访问数组数据,并且需要使用 fixed 关键字来固定指针,示例如下:
- using System;
- namespace UnsafeCodeApplication
- {
- class TestPointer
- {
- public unsafe static void Main()
- {
- int[] list = {10, 100, 200};
- fixed(int *ptr = list)
- /* let us have array address in pointer */
- for ( int i = 0; i < 3; i++)
- {
- Console.WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i));
- Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
- }
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- Address of list[0] = 31627168
- Value of list[0] = 10
- Address of list[1] = 31627172
- Value of list[1] = 100
- Address of list[2] = 31627176
- Value of list[2] = 200
编译不安全代码
必须切换命令行编译器到指定的 /unsafe 命令行才能进行不安全代码的编译。
例如,编译一个包含不安全代码的名为 prog1.cs 的程序,需要在命令行中输入如下命令:
- csc /unsafe prog1.cs
在 Visual Studio IDE 环境中编译不安全代码,需要在项目属性中启用相关设置。
步骤如下:
- 双击资源管理器中的属性节点,打开项目属性。
- 点击 Build 标签页。
- 选择选项 "Allow unsafe code"。
多线程
线程的定义是程序的执行路径。每个线程都定义了一个独特的控制流,如果应用程序涉及到复杂且耗时的操作,那么设置不同的线程执行路径会非常有好处,因为每个线程会被指定于执行特定的工作。
线程实际上是轻量级进程。一个常见的使用线程的实例是现代操作系统中的并行编程。使用线程不仅有效地减少了 CPU 周期的浪费,同时还提高了应用程序的运行效率。
到目前为止我们所编写的程序都是以一个单线程作为应用程序的运行的,其运行过程均为单一的。但是,在这种情况下,应用程序在同一时间只能执行一个任务。为了使应用程序可以同时执行多个任务,需要将其被划分为多个更小的线程。
线程的声明周期
线程的生命周期开始于对象的 System.Threading.Thread 类创建时,结束于线程被终止或是完成执行时。 下列各项为线程在生命周期中的各种状态:
- 未启动状态:线程实例已被创建但 Start 方法仍未被调用时的状态。
- 就绪状态:线程已准备好运行,正在等待 CPU 周期时的状态。
- 不可运行状态:下面的几种情况下线程是不可运行的:
- 已经调用 Sleep 方法
- 已经调用 Wait 方法
- 通过 I/O 操作阻塞
- 死亡状态:线程已完成执行或已终止的状态。
主线程
在 C# 中,System.Threading.Thread 类用于线程的工作。它允许创建并访问多线程应用程序中的单个线程。进程中第一个被执行的线程称为主线程。
当 C# 程序开始执行时,会自动创建主线程。使用 Thread 类创建的线程被主线程的子线程调用。通过 Thread 类的 CurrentThread 属性可以访问线程。
下面的程序演示了主线程的执行:
- using System;
- using System.Threading;
- namespace MultithreadingApplication
- {
- class MainThreadProgram
- {
- static void Main(string[] args)
- {
- Thread th = Thread.CurrentThread;
- th.Name = "MainThread";
- Console.WriteLine("This is {0}", th.Name);
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- This is MainThread
Thread 类的属性和方法
下表为 Thread 类一些常用的属性:
属性 | 描述 |
---|---|
CurrentContext | 获取线程当前正在执行的线程的上下文。 |
CurrentCulture | 获取或设置当前线程的区域性 |
CurrentPrinciple | 获取或设置线程的当前责任人(针对基于角色的安全性) |
CurrentThread | 获取当前正在运行的线程 |
CurrentUICulture | 获取或设置资源管理器当前所使用的区域性,便于在运行时查找区域性特定的资源 |
ExecutionContext | 获取一个 ExcutionContext 对象,该对象包含有关当前线程的各种上下文信息。 |
IsAlive | 获取一个值,指示当前线程的执行状态。 |
IsBackground | 获取或设置一个值,指示线程是否为后台线程。 |
IsThreadPoolThread | 获取或设置一个值,指示线程是否属于托管线程池。 |
ManagedThreadId | 获取当前托管线程的唯一标识符 |
Name | 获取或设置线程的名称。 |
Priority | 获取或设置一个值,指示线程的调度优先级 |
ThreadState | 获取一个值,指示当前线程的状态。 |
下表为 Thread 类一些常用的方法:
序号 | 方法名和描述 |
---|---|
1 | public void Abort() 在调用此方法的线程上引发 ThreadAbortException,则触发终止此线程的操作。调用此方法通常会终止线程。 |
2 | public static LocalDataStoreSlot AllocateDataSlot() 在所有的线程上分配未命名的数据槽。使用以 ThreadStaticAttribute 属性标记的字段,可获得更好的性能。 |
3 | public static LocalDataStoreSlot AllocateNamedDataSlot( string name) 在所有线程上分配已命名的数据槽。使用以 ThreadStaticAttribute 属性标记的字段,可获得更好的性能。 |
4 | public static void BeginCriticalRegion() 通知主机将要进入一个代码区域,若该代码区域内的线程终止或发生未经处理的异常,可能会危害应用程序域中的其他任务。 |
5 | public static void BeginThreadAffinity() 通知主机托管代码将要执行依赖于当前物理操作系统线程的标识的指令。 |
6 | public static void EndCriticalRegion() 通知主机将要进入一个代码区域,若该代码区域内的线程终止或发送未经处理的异常,仅会影响当前任务。 |
7 | public static void EndThreadAffinity() 通知主机托管代码已执行完依赖于当前物理操作系统线程的标识的指令。 |
8 | public static void FreeNamedDataSlot(string name) 消除进程中所有线程的名称与槽之间的关联。使用以 ThreadStaticAttribute 属性标记的字段,可获得更好的性能。 |
9 | public static Object GetData( LocalDataStoreSlot slot ) 在当前线程的当前域中从当前线程上指定的槽中检索值。使用以 ThreadStaticAttribute 属性标记的字段,可获得更好的性能。 |
10 | public static AppDomain GetDomain() 返回当前线程正在其中运行的当前域。 |
11 | public static AppDomain GetDomainID() 返回唯一的应用程序域标识符。 |
12 | public static LocalDataStoreSlot GetNamedDataSlot( string name ) 查找已命名的数据槽。使用以 ThreadStaticAttribute 属性标记的字段,可获得更好的性能。 |
13 | public void Interrupt() 中断处于 WaitSleepJoin 线程状态的线程。 |
14 | public void Join() 在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止。此方法有不同的重载形式。 |
15 | public static void MemoryBarrier() 按如下方式同步内存存取:执行当前线程的处理器在对指令进行重新排序时,不能采用先执行 MemoryBarrier 调用之后的内存存取,再执行 MemoryBarrier 调用之前的内存存取的方式。 |
16 | public static void ResetAbort() 取消当前线程请求的 Abort 操作。 |
17 | public static void SetData( LocalDataStoreSlot slot, Object data ) 在指定槽中,设置当前正在运行中线程的当前域的数据。使用以 ThreadStaticAttribute 属性标记的字段,可获得更好的性能。 |
18 | public void Start() 开始一个线程。 |
19 | public static void Sleep( int millisecondsTimeout ) 令线程暂停一段时间。 |
20 | public static void SpinWait( int iterations ) 令线程等待一段时间,时间长度由 iterations 参数定义。 |
21 | public static byte VolatileRead( ref byte address );public static double VolatileRead( ref double address );public static int VolatileRead( ref int address );public static Object VolatileRead( ref Object address ) 读取字段的值。无论处理器的数目或处理器缓存的状态如何,该值都表示由计算机中任何一个处理器写入的最新值。此方法有不同的重载形式,此处仅给出部分例子。 |
22 | public static void VolatileWrite( ref byte address, byte value );public static void VolatileWrite( ref double address, double value );public static void VolatileWrite( ref int address, int value );public static void VolatileWrite( ref Object address, Object value ) 立即写入一个值到字段中,使该值对计算机中的所有处理器都可见。此方法有不同的重载形式,此处仅给出部分例子。 |
23 | public static bool Yield() 令调用线程执行已准备好在当前处理器上运行的另一个线程,由操作系统选择要执行的线程。 |
线程的创建
线程是通过扩展 Thread 类创建的,扩展而来的 Thread 类调用 Start() 方法即可开始子线程的执行。 示例:
- using System;
- using System.Threading;
- namespace MultithreadingApplication
- {
- class ThreadCreationProgram
- {
- public static void CallToChildThread()
- {
- Console.WriteLine("Child thread starts");
- }
- static void Main(string[] args)
- {
- ThreadStart childref = new ThreadStart(CallToChildThread);
- Console.WriteLine("In Main: Creating the Child thread");
- Thread childThread = new Thread(childref);
- childThread.Start();
- Console.ReadKey();
- }
- }
- }
编译执行上述代码段,得到如下结果:
- In Main: Creating the Child thread
- Child thread starts
线程的管理
Thread 类提供了多种用于线程管理的方法。 下面的示例调用了 sleep() 方法来在一段特定时间内暂停线程:
- using System;
- using System.Threading;
- namespace MultithreadingApplication
- {
- class ThreadCreationProgram
- {
- public static void CallToChildThread()
- {
- Console.WriteLine("Child thread starts");
- // 令线程暂停 5000 毫秒
- int sleepfor = 5000;
- Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
- Thread.Sleep(sleepfor);
- Console.WriteLine("Child thread resumes");
- }
- static void Main(string[] args)
- {
- ThreadStart childref = new ThreadStart(CallToChildThread);
- Console.WriteLine("In Main: Creating the Child thread");
- Thread childThread = new Thread(childref);
- childThread.Start();
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下代码段:
- In Main: Creating the Child thread
- Child thread starts
- Child Thread Paused for 5 seconds
- Child thread resumes
线程的销毁
使用 Abort() 方法可销毁线程。
在运行时,通过抛出 ThreadAbortException 来终止线程。这个异常无法被捕获,当且仅当具备 finally 块时,才将控制送到 finally 块中。
示例:
- using System;
- using System.Threading;
- namespace MultithreadingApplication
- {
- class ThreadCreationProgram
- {
- public static void CallToChildThread()
- {
- try
- {
- Console.WriteLine("Child thread starts");
- // 执行一些任务,如计十个数
- for (int counter = 0; counter <= 10; counter++)
- {
- Thread.Sleep(500);
- Console.WriteLine(counter);
- }
- Console.WriteLine("Child Thread Completed");
- }
- catch (ThreadAbortException e)
- {
- Console.WriteLine("Thread Abort Exception");
- }
- finally
- {
- Console.WriteLine("Couldn't catch the Thread Exception");
- }
- }
- static void Main(string[] args)
- {
- ThreadStart childref = new ThreadStart(CallToChildThread);
- Console.WriteLine("In Main: Creating the Child thread");
- Thread childThread = new Thread(childref);
- childThread.Start();
- // 将主线程停止一段时间
- Thread.Sleep(2000);
- // 中止子线程
- Console.WriteLine("In Main: Aborting the Child thread");
- childThread.Abort();
- Console.ReadKey();
- }
- }
- }
编译执行上述代码,得到如下结果:
- In Main: Creating the Child thread
- Child thread starts
- 0
- 1
- 2
- In Main: Aborting the Child thread
- Thread Abort Exception
- Couldn't catch the Thread Exception