C# 里定义集合的最简单方法是 继承 CollectionBase 类
using System;
using System.Collections;
public class Collection : CollectionBase
{
public void Add(Object item)
{
InnerList.Add(item);
}
public void Remove(Object item)
{
InnerList.Remove(item);
}
public new void Clear()
{
InnerList.Clear();
}
public new int Count()
{
return InnerList.Count;
}
}
class chapter1
{
static void Main()
{
Collection names = new Collection();
names.Add("David");
names.Add("Bernica");
names.Add("Raymond");
names.Add("Clayton");
foreach (Object name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Number of names: " + names.Count());
names.Remove("Raymond");
Console.WriteLine("Number of names: " + names.Count());
names.Clear();
Console.WriteLine("Number of names: " + names.Count());
}
}
泛型函数
static void Swap<T>(ref T val1, ref T val2)
{
T temp;
temp = val1;
val1 = val2;
val2 = temp;
}
泛型函数
static void Main()
{
int num1 = 100;
int num2 = 200;
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);
Swap<int>(ref num1, ref num2);
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);
string str1 = "Sam";
string str2 = "Tom";
Console.WriteLine("String 1: " + str1);
Console.WriteLine("String 2: " + str2);
Swap<string>(ref str1, ref str2);
Console.WriteLine("String 1: " + str1);
Console.WriteLine("String 2: " + str2);
}
static void Swap<T>(ref T val1, ref T val2)
{
T temp;
temp = val1;
val1 = val2;
val2 = temp;
}
}
泛型类
public class Node<T>
{
T data;
Node<T> link;
public Node(T data, Node<T> link)
{
this.data = data;
this.link = link;
}
}
Node<string> node1 = new Node<string>("Mike", null);
Node<string> node2 = new Node<string>("Raymond", node1);
static void DisplayNums(int[] arr)
{
for (int i = 0; i <= arr.GetUpperBound(0); i++)
Console.Write(arr[i] + " ");
}
时间测试
在。Net 环境中,需要考虑程序运行所处的线程以及无用单元收集可能在任何时候发生。
public class Timing
{
TimeSpan startingTime;
TimeSpan duration;
public Timing()
{
startingTime = new TimeSpan(0);
duration = new TimeSpan(0);
}
public void StopTime()
{
duration =
Process.GetCurrentProcess().Threads[0].
UserProcessorTime.Subtract(startingTime);
}
public void startTime()
{
GC.Collect();
GC.WaitForPendingFinalizers(); // Finalizers()是存储在堆中对象拆除对象的最后一步。
startingTime =
Process.GetCurrentProcess().Threads[0].
UserProcessorTime;
}
public TimeSpan Result()
{
return duration;
}
}
static void Main()
{
int[] nums = new int[100000];
BuildArray(nums);
Timing tObj = new Timing();
tObj.startTime();
DisplayNums(nums);
tObj.stopTime();
Console.WriteLine("time (.NET): " + tObj.Result().TotalSeconds);
}
static void BuildArray(int[] arr)
{
for (int i = 0; i < 100000; i++)
arr[i] = i;
}
static void DisplayNums(int[] arr)
{
for (int i = 0; i <= arr.GetUpperBound(0); i++)
Console.Write(arr[i] + " ");