例子如下:
static void Main(string[] args)
{
int x=5, y=10;
Swqp<int>(ref x, ref y);
Console.WriteLine("{0},{1}",x, y);
String st1 = "abc", st2 = "xyz";
Swqp<string>(ref st1, ref st2);
Console.WriteLine("{0},{1}", st1, st2);
}
static void Swqp<T>(ref T a, ref T b)
{
T temp;
temp = a;
a = b;
b = temp;
}
这也是泛型的使用,通过函数添加二叉树的节点。
public class Tree<TItem> where TItem:IComparable<TItem>
{
public TItem NodeData { get; set; }
public Tree<TItem> LeftTree { get; set; }
public Tree<TItem> RightTree { get; set; }
public Tree(TItem nodeValue)
{
this.NodeData = nodeValue;
this.LeftTree = null;
this.RightTree = null;
}
public void Insert(TItem newItem )
{
TItem currentNodeValue = this.NodeData;
if (currentNodeValue.CompareTo(newItem) > 0)
{
if (LeftTree == null)
{
this.LeftTree = new Tree<TItem>(newItem);
}
else
{
this.LeftTree.Insert(newItem);
}
}
else
{
if (RightTree == null)
{
this.RightTree = new Tree<TItem>(newItem);
}
else
{
this.RightTree.Insert(newItem);
}
}
}
public void WalkTree()
{
if (this.LeftTree != null)
{
LeftTree.WalkTree();
}
Console.WriteLine(this.NodeData.ToString());
if (this.RightTree != null)
{
RightTree.WalkTree();
}
}
}
class Program
{
static void Main(string[] args)
{
/*
Tree<int> t = new Tree<int>(10);
t.Insert(4);
t.Insert(3);
t.Insert(5);
t.Insert(14);
t.Insert(25);
*
t.WalkTree();
*/
Tree<char> charTree = new Tree<char>('M');
InsertIntoTree<char>(charTree, 'A', 'B', 'O', 'N', 'Z', 'C');
charTree.WalkTree();
}
static void InsertIntoTree<TItem>(Tree<TItem> tree, params TItem[] data)
where TItem :IComparable<TItem>
{
if (data.Length == 0)
throw new ArgumentException("most provide at least on data value");
foreach(TItem datum in data)
{
tree.Insert(datum);
}
}
泛型接口和泛型类
interface IWrapper<T>
{
void setData(T data);
T GetData();
}
class A<T> : IWrapper<T>
{
private T A_data;
void IWrapper<T>.setData(T data)
{
this.A_data = data;
}
T IWrapper<T>.GetData()
{
return this.A_data;
}
}
static void Main(string[] args)
{
A<string> A_string = new A<string>();
IWrapper<string> Iw = A_string;
Iw.setData("abc");
Console.WriteLine("{0}",Iw.GetData());
}
C#自带的队列,也可以使用泛型的形式来使用
using System.Collections;
static void Main(string[] args) { int a = 5; double b = 6; Queue <int>s = new Queue<int>();//表示是一个int类型的队列,只能存放int类型,不带泛型的存放的是object类型 s.Enqueue(a); // s.Enqueue(b);//存放double会出错 while (s.Count > 0) { Console.WriteLine(s.Dequeue().ToString()); } }