37.集合
集合(Collection)类是专门用于数据存储和检索的类。这些类提供了对栈(stack)、队列(queue)、列表(list)和哈希表(hash table)的支持。大多数集合类实现了相同的接口。
集合(Collection)类服务于不同的目的,如为元素动态分配内存,基于索引访问列表项等等。这些类创建 Object 类的对象的集合。在 C# 中,Object 类是所有数据类型的基类。
下述常用的 System.Collection 命名空间的类
动态数组(ArrayList):有序、有索引、动态调整大小(自动扩容)、动态内存分配
描述和用法概述:
它代表了可被单独索引的对象的有序集合。
它基本上可以替代一个数组。但是,与数组不同的是,您可以使用索引在指定的位置添加和移除项目,动态数组会自动重新调整它的大小。
它也允许在列表中进行动态内存分配、增加、搜索、排序各项。
常用属性
Capacity 获取或设置 ArrayList 可以包含的元素个数。
Count 获取 ArrayList 中实际包含的元素个数。
IsFixedSize 获取一个值,表示 ArrayList 是否具有固定大小。
IsReadOnly 获取一个值,表示 ArrayList 是否只读。
IsSynchronized 获取一个值,表示访问 ArrayList 是否同步(线程安全)。
Item[Int32] 获取或设置指定索引处的元素。
SyncRoot 获取一个对象用于同步访问 ArrayList。
常用方法
1 public virtual int Add( object value );
在 ArrayList 的末尾添加一个对象。
2 public virtual void AddRange( ICollection c );
在 ArrayList 的末尾添加 ICollection 的元素。
3 public virtual void Clear();
从 ArrayList 中移除所有的元素。
4 public virtual bool Contains( object item );
判断某个元素是否在 ArrayList 中。
5 public virtual ArrayList GetRange( int index, int count );
返回一个 ArrayList,表示源 ArrayList 中元素的子集。
6 public virtual int IndexOf(object);
返回某个值在 ArrayList 中第一次出现的索引,索引从零开始。
7 public virtual void Insert( int index, object value );
在 ArrayList 的指定索引处,插入一个元素。
8 public virtual void InsertRange( int index, ICollection c );
在 ArrayList 的指定索引处,插入某个集合的元素。
9 public virtual void Remove( object obj );
从 ArrayList 中移除第一次出现的指定对象。
10 public virtual void RemoveAt( int index );
移除 ArrayList 的指定索引处的元素。
11 public virtual void RemoveRange( int index, int count );
从 ArrayList 中移除某个范围的元素。
12 public virtual void Reverse();
逆转 ArrayList 中元素的顺序。
13 public virtual void SetRange( int index, ICollection c );
复制某个集合的元素到 ArrayList 中某个范围的元素上。
14 public virtual void Sort();
对 ArrayList 中的元素进行排序。
15 public virtual void TrimToSize();
设置容量为 ArrayList 中元素的实际个数。
实例:
using System;
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
Console.WriteLine("Adding some numbers:");
al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);
Console.WriteLine("Capacity: {0} ", al.Capacity);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("Content: ");
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
哈希表(HashTable): 类代表了一系列基于键的哈希代码组织起来的键/值对
它使用键来访问集合中的元素。
当您使用键访问元素时,则使用哈希表,而且您可以识别一个有用的键值。哈希表中的每一项都有一个键/值对。键用于访问集合中的项目。
常用属性:
Count 获取 Hashtable 中包含的键值对个数。
IsFixedSize 获取一个值,表示 Hashtable 是否具有固定大小。
IsReadOnly 获取一个值,表示 Hashtable 是否只读。
Item 获取或设置与指定的键相关的值。
Keys 获取一个 ICollection,包含 Hashtable 中的键。
Values 获取一个 ICollection,包含 Hashtable 中的值。
常用方法:
1 public virtual void Add( object key, object value );
向 Hashtable 添加一个带有指定的键和值的元素。
2 public virtual void Clear();
从 Hashtable 中移除所有的元素。
3 public virtual bool ContainsKey( object key );
判断 Hashtable 是否包含指定的键。
4 public virtual bool ContainsValue( object value );
判断 Hashtable 是否包含指定的值。
5 public virtual void Remove( object key );
从 Hashtable 中移除带有指定的键的元素。
实例
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("001", "Zara Ali");
ht.Add("002", "Abida Rehman");
ht.Add("003", "Joe Holzner");
ht.Add("004", "Mausam Benazir Nur");
ht.Add("005", "M. Amlan");
ht.Add("006", "M. Arif");
ht.Add("007", "Ritesh Saikia");
if (ht.ContainsValue("Nuha Ali"))
{
Console.WriteLine("This student name is already in the list");
}
else
{
ht.Add("008", "Nuha Ali");
}
// 获取键的集合
ICollection key = ht.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
}
Console.ReadKey();
//输出结果:
007: Ritesh Saikia
004: Mausam Benazir Nur
005: M. Amlan
008: Nuha Ali
002: Abida Rehman
003: Joe Holzner
001: Zara Ali
006: M. Arif
}
}
}
排序列表(SortedList)
SortedList 类代表了一系列按照键来排序的键/值对,这些键值对可以通过键和索引来访问。
它可以使用键和索引来访问列表中的项。
排序列表是数组和哈希表的组合。它包含一个可使用键或索引访问各项的列表。
如果您使用索引访问各项,则它是一个动态数组(ArrayList),如果您使用键访问各项,则它是一个哈希表(Hashtable)。
集合中的各项总是按键值排序。
常用属性:
Capacity 获取或设置 SortedList 的容量。
Count 获取 SortedList 中的元素个数。
IsFixedSize 获取一个值,表示 SortedList 是否具有固定大小。
IsReadOnly 获取一个值,表示 SortedList 是否只读。
Item 获取或设置与 SortedList 中指定的键相关的值。
Keys 获取 SortedList 中的键。
Values 获取 SortedList 中的值。
常用方法:
1 public virtual void Add( object key, object value );
向 SortedList 添加一个带有指定的键和值的元素。
2 public virtual void Clear();
从 SortedList 中移除所有的元素。
3 public virtual bool ContainsKey( object key );
判断 SortedList 是否包含指定的键。
4 public virtual bool ContainsValue( object value );
判断 SortedList 是否包含指定的值。
5 public virtual object GetByIndex( int index );
获取 SortedList 的指定索引处的值。
6 public virtual object GetKey( int index );
获取 SortedList 的指定索引处的键。
7 public virtual IList GetKeyList();
获取 SortedList 中的键。
8 public virtual IList GetValueList();
获取 SortedList 中的值。
9 public virtual int IndexOfKey( object key );
返回 SortedList 中的指定键的索引,索引从零开始。
10 public virtual int IndexOfValue( object value );
返回 SortedList 中的指定值第一次出现的索引,索引从零开始。
11 public virtual void Remove( object key );
从 SortedList 中移除带有指定的键的元素。
12 public virtual void RemoveAt( int index );
移除 SortedList 的指定索引处的元素。
13 public virtual void TrimToSize();
设置容量为 SortedList 中元素的实际个数。
实例:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add("001", "Zara Ali");
sl.Add("002", "Abida Rehman");
sl.Add("003", "Joe Holzner");
sl.Add("004", "Mausam Benazir Nur");
sl.Add("005", "M. Amlan");
sl.Add("006", "M. Arif");
sl.Add("007", "Ritesh Saikia");
if (sl.ContainsValue("Nuha Ali"))
{
Console.WriteLine("This student name is already in the list");
}
else
{
sl.Add("008", "Nuha Ali");
}
// 获取键的集合
ICollection key = sl.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + sl[k]);
}
//输出结果:
001: Zara Ali
002: Abida Rehman
003: Joe Holzner
004: Mausam Banazir Nur
005: M. Amlan
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali
}
}
}
堆栈(Stack)
它代表了一个后进先出的对象集合。
当您需要对各项进行后进先出的访问时,则使用堆栈。当您在列表中添加一项,称为推入元素,当您从列表中移除一项时,称为弹出元素。
常用属性:
Count 获取 Stack 中包含的元素个数。
常用方法:
1 public virtual void Clear();
从 Stack 中移除所有的元素。
2 public virtual bool Contains( object obj );
判断某个元素是否在 Stack 中。
3 public virtual object Peek();
返回在 Stack 的顶部的对象,但不移除它。
4 public virtual object Pop();
移除并返回在 Stack 的顶部的对象。
5 public virtual void Push( object obj );
向 Stack 的顶部添加一个对象。
6 public virtual object[] ToArray();
复制 Stack 到一个新的数组中。
实例:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
Console.WriteLine();
st.Push('V');
st.Push('H');
Console.WriteLine("The next poppable value in stack: {0}",
st.Peek());
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
Console.WriteLine();
Console.WriteLine("Removing values ");
st.Pop();
st.Pop();
st.Pop();
Console.WriteLine("Current stack: ");
foreach (char c in st)
{
Console.Write(c + " ");
}
//输出结果:
Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A
}
}
}
队列(Queue)
它代表了一个先进先出的对象集合。
当您需要对各项进行先进先出的访问时,则使用队列。当您在列表中添加一项,称为入队,当您从列表中移除一项时,称为出队。
常见属性:
Count 获取 Queue 中包含的元素个数。
常见方法:
1 public virtual void Clear();
从 Queue 中移除所有的元素。
2 public virtual bool Contains( object obj );
判断某个元素是否在 Queue 中。
3 public virtual object Dequeue();
移除并返回在 Queue 的开头的对象。
4 public virtual void Enqueue( object obj );
向 Queue 的末尾添加一个对象。
5 public virtual object[] ToArray();
复制 Queue 到一个新的数组中。
6 public virtual void TrimToSize();
实例:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Queue q = new Queue();
q.Enqueue('A');
q.Enqueue('M');
q.Enqueue('G');
q.Enqueue('W');
Console.WriteLine("Current queue: ");
foreach (char c in q)
Console.Write(c + " ");
Console.WriteLine();
q.Enqueue('V');
q.Enqueue('H');
Console.WriteLine("Current queue: ");
foreach (char c in q)
Console.Write(c + " ");
Console.WriteLine();
Console.WriteLine("Removing values ");
char ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
Console.ReadKey();
//输出结果:
Current queue:
A M G W
Current queue:
A M G W V H
Removing values
The removed value: A
The removed value: M
}
}
}
点阵列(BitArray):管理一个紧凑型的数组,
它代表了一个使用值 1 和 0 来表示的二进制数组。它使用布尔值来表示,其中 true 表示位是开启的(1),false 表示位是关闭的(0)。
当您需要存储位,但是事先不知道位数时,则使用点阵列。您可以使用整型索引从点阵列集合中访问各项,索引从零开始。
常用属性:
Count 获取 BitArray 中包含的元素个数。
IsReadOnly 获取一个值,表示 BitArray 是否只读。
Item 获取或设置 BitArray 中指定位置的位的值。
Length 获取或设置 BitArray 中的元素个数。
常用方法:
1 public BitArray And( BitArray value );
对当前的 BitArray 中的元素和指定的 BitArray 中的相对应的元素执行按位与操作。
2 public bool Get( int index );
获取 BitArray 中指定位置的位的值。
3 public BitArray Not();
把当前的 BitArray 中的位值反转,以便设置为 true 的元素变为 false,设置为 false 的元素变为 true。
4 public BitArray Or( BitArray value );
对当前的 BitArray 中的元素和指定的 BitArray 中的相对应的元素执行按位或操作。
5 public void Set( int index, bool value );
把 BitArray 中指定位置的位设置为指定的值。
6 public void SetAll( bool value );
把 BitArray 中的所有位设置为指定的值。
7 public BitArray Xor( BitArray value );
对当前的 BitArray 中的元素和指定的 BitArray 中的相对应的元素执行按位异或操作(如果两个元素一致,则为0;两个元素不一致,则结果为1)。
实例:
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
// 创建两个大小为 8 的点阵列
BitArray ba1 = new BitArray(8);
BitArray ba2 = new BitArray(8);
byte[] a = { 60 };//00111100
byte[] b = { 13 };//00001101
// 把值 60 和 13 存储到点阵列中
ba1 = new BitArray(a);
ba2 = new BitArray(b);
// ba1 的内容
Console.WriteLine("Bit array ba1: 60");
for (int i = 0; i < ba1.Count; i++)
{
Console.Write("{0, -6} ", ba1[i]);
}
Console.WriteLine();
// ba2 的内容
Console.WriteLine("Bit array ba2: 13");
for (int i = 0; i < ba2.Count; i++)
{
Console.Write("{0, -6} ", ba2[i]);
}
Console.WriteLine();
BitArray ba3 = new BitArray(8);
ba3 = ba1.And(ba2);
// ba3 的内容
Console.WriteLine("Bit array ba3 after AND operation: 12");
for (int i = 0; i < ba3.Count; i++)
{
Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
ba3 = ba1.Or(ba2);
// ba3 的内容
Console.WriteLine("Bit array ba3 after OR operation: 61");
for (int i = 0; i < ba3.Count; i++)
{
Console.Write("{0, -6} ", ba3[i]);
}
Console.WriteLine();
Console.ReadKey();
//输出结果:
Bit array ba1: 60 // 00111100
False False True True True True False False
Bit array ba2: 13 // 10110000
True False True True False False False False
Bit array ba3 after AND operation: 12 // 00110000
False False True True False False False False
Bit array ba3 after OR operation: 61
True False True True False False False False
}
}
}
38.泛型(Generic)
使用 <> 表示
泛型(Generic) 允许延迟编写类或方法中的编程元素的数据类型的规范,直到实际在程序中使用它的时候。换句话说,泛型允许编写一个可以与任何数据类型一起工作的类或方法。
可以通过数据类型的替代参数编写类或方法的规范。当编译器遇到类的构造函数或方法的函数调用时,它会生成代码来处理指定的数据类型。
实例:声明int的泛型
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
}
}
}
泛型(Generic)特性
使用泛型是一种增强程序功能的技术,具体表现在以下几个方面:
它有助于最大限度地重用代码、保护类型的安全以及提高性能。
可以创建泛型集合类。.NET 框架类库在 System.Collections.Generic 命名空间中包含了一些新的泛型集合类。您可以使用这些泛型集合类来替代 System.Collections 中的集合类。
可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。
可以对泛型类进行约束以访问特定数据类型的方法。
关于泛型数据类型中使用的类型的信息可在运行时通过使用反射获取。
泛型(Generic)方法,可通过类型参数声明泛型方法,实例如下:
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
}
}
}
泛型(Generic)委托,通过类型参数定义泛型委托
语法: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
}
}
}
39.匿名方法
在 C# 中,匿名函数是一种没有名字的方法,可以在代码中定义和使用。
我们已经提到过,委托是用于引用与其具有相同标签的方法。换句话说,可以使用委托对象调用可由委托引用的方法。
匿名方法(Anonymous methods) 提供了一种传递代码块作为委托参数的技术。
在匿名方法中您不需要指定返回类型,它是从方法主体内的 return 语句推断的。
Lambda表达式
简洁的语法,用于创建匿名函数,通常用于LINQ查询和委托。
语法:(parameters) => expression // 或 (parameters) => { statement; }
实例:
// 示例:使用 Lambda 表达式定义一个委托
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(2, 3)); // 输出 5
// 示例:使用 Lambda 表达式过滤数组中的元素
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // 输出 2 4
}
匿名方法:通过使用 delegate 关键字创建委托实例来声明的
语法:delegate(parameters) { statement; }
例如:
delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
代码块 Console.WriteLine("Anonymous Method: {0}", x); 是匿名方法的主体。
委托可以通过匿名方法调用,也可以通过命名方法调用,即,通过向委托对象传递方法参数。
注意: 匿名方法的主体后面需要一个 ;。例如:nc(10);
实例:
// 示例:使用匿名方法定义一个委托
Func<int, int, int> multiply = delegate (int a, int b)
{
return a * b;
};
Console.WriteLine(multiply(2, 3)); // 输出 6
// 示例:使用匿名方法作为事件处理程序
Button button = new Button();
button.Click += delegate (object sender, EventArgs e)
{
Console.WriteLine("Button clicked!");
};
实例2:着重使用委托演示匿名方法的概念
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);
}
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();
}
}
}
实例3:C# 2.0 及更高版本中,引入了 lambda 表达式,它是一种更简洁的语法形式,用于编写匿名方法。使用Lambda表达式演示委托匿名方法
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);
}
static void Main(string[] args)
{
// 使用 lambda 表达式创建委托实例
NumberChanger nc = x => Console.WriteLine($"Lambda Expression: {x}");
// 使用 lambda 表达式调用委托
nc(10);
// 使用命名方法实例化委托
nc = new NumberChanger(AddNum);
// 使用命名方法调用委托
nc(5);
// 使用另一个命名方法实例化委托
nc = new NumberChanger(MultNum);
// 使用命名方法调用委托
nc(2);
Console.ReadKey();
//输出结果
Lambda Expression: 10
Named Method: 15
Named Method: 30
}
}
}
40.不安全代码
当一个代码块使用 unsafe 修饰符标记时,C# 允许在函数中使用指针变量。不安全代码或非托管代码是指使用了指针变量的代码块。
指针变量
指针是指为另一个变量的地址的变量,即,内存位置的直接地址。就像其他变量或常量,您必须在使用指针存储其他变量地址之前声明指针。
指针变量的声明一般形式:type* var-name;
指针类型声明的实例:
int* p p 是指向整数的指针。
double* p p 是指向双精度数的指针。
float* p p 是指向浮点数的指针。
int** p p 是指向整数的指针的指针。
int*[] p p 是指向整数的指针的一维数组。
char* p p 是指向字符的指针。
void* p p 是指向未知类型的指针。
在同一个声明中声明多个指针时,星号 * 仅与基础类型一起写入;而不是用作每个指针名称的前缀。例如:
int* p1, p2, p3; // 正确
int *p1, *p2, *p3; // 错误
实例:说明了 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 是不同的类型。您可以增加指针变量 p,因为它在内存中不是固定的,但是数组地址在内存中是固定的,所以您不能增加数组 p。
因此,如果您需要使用指针变量访问数组数据,可以像我们通常在 C 或 C++ 中所做的那样,使用 fixed 关键字来固定指针。
实例:
using System;
namespace UnsafeCodeApplication
{
class TestPointer
{
public unsafe static void Main()
{
int[] list = {10, 100, 200};
fixed(int *ptr = list)
/* 显示指针中数组地址 */
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,那么您需要在项目属性中启用不安全代码。步骤如下:
通过双击资源管理器(Solution Explorer)中的属性(properties)节点,打开项目属性(project properties)。
点击 Build 标签页。
选择选项"Allow unsafe code"。
41.多线程
线程 被定义为程序的执行路径。每个线程都定义了一个独特的控制流。如果应用程序涉及到复杂的和耗时的操作,那么设置不同的线程执行路径往往是有益的,每个线程执行特定的工作。
线程是轻量级进程。一个使用线程的常见实例是现代操作系统中并行编程的实现。使用线程节省了 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常用的属性和方法
常用属性:
CurrentContext 获取线程正在其中执行的当前上下文。
CurrentCulture 获取或设置当前线程的区域性。
CurrentPrincipal 获取或设置线程的当前负责人(对基于角色的安全性而言)。
CurrentThread 获取当前正在运行的线程。
CurrentUICulture 获取或设置资源管理器使用的当前区域性以便在运行时查找区域性特定的资源。
ExecutionContext 获取一个 ExecutionContext 对象,该对象包含有关当前线程的各种上下文的信息。
IsAlive 获取一个值,该值指示当前线程的执行状态。
IsBackground 获取或设置一个值,该值指示某个线程是否为后台线程。
IsThreadPoolThread 获取一个值,该值指示线程是否属于托管线程池。
ManagedThreadId 获取当前托管线程的唯一标识符。
Name 获取或设置线程的名称。
Priority 获取或设置一个值,该值指示线程的调度优先级。
ThreadState 获取一个值,该值包含当前线程的状态。
常用方法:
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;
sing System.Threading;
amespace MultithreadingApplication
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
// 计数到 10
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
}
}