了解委托的人都知道C#中的委托相当于C++中的函数指针,但相当于C++中的函数指针来讲,它是面向对象的,是类型安全的,具有众多的优点。C#中的委托多用于构造事件。
本 文是C#委托的一个简单示例,主要是说明C#中委托的使用方法,并依此实现在一个排序函数中按指定的排序规则对数组进行排序。
以下是详细的源码。
//
声明一个委托
private
delegate
bool
SortDelegate(
double
num1,
double
num2);

//
委托SortDelegate的实例Sd作为排序Sort函数是一个形参是为了给排序指定排序规则,如:从小到大,从大到小
//
或按每个数字的各位数之和从小到大或从大到小进行排序(对于浮点数,位数只计算小数点之前的)
//
在调用时Sd需传入一个函数的函数名
private
string
Sort(
string
Org,SortDelegate Sd)

...
{
string[] Old = Org.Split(',');
int Len = Old.Length;
for(int i=0;i<Len;i++)
if(!IsNumeric(Old[i]))

...{
MessageBox.Show("对不起,您输入的不是数字,不能排序。");
return " ";
}
double[] Num = new double[Len];
for (int i = 0; i < Len; i++)

...{

Num[i] = double.Parse(Old[i]);
}
//调用冒泡排序法
BubbleSort(ref Num,Sd);

string Res="";
for (int i = 0; i < Len; i++)

...{
Res += Num[i].ToString();
if (i != Len-1)
Res += " ";
}
return Res;
}
static
bool
IsNumeric(
string
str)

...
{
if (str == null || str.Length == 0)
return false;
foreach (char c in str)

...{
if (!Char.IsNumber(c))

...{
return false;
}
}
return true;
}

//
冒泡法排序
private
void
BubbleSort(
ref
double
[] num, SortDelegate Sd)

...
{
int Len = num.Length;
for (int i = 1; i < Len; i++)
for (int j = 0; j < Len-i; j++)

...{
if (!Sd(num[j], num[j+1]))

...{
double temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
//
按各位数和从小到大排序函数,浮点数小数点后的数字忽略
private
bool
BitSmallSort(
double
Num1,
double
Num2)

...
{
int n1 = (int)Num1, n2 = (int)Num2;
int s1 = 0, s2 = 0;
while (n1!=0)

...{
s1 += n1 % 10;
n1 /= 10;
}
while (n2!=0)

...{
s2 += n2 % 10;
n2 /= 10;
}
return s1<s2;
}
//
按各位数和从小到大排序函数
private
bool
BitBigSort(
double
Num1,
double
Num2)

...
{
return !BitSmallSort(Num1, Num2);
}
//
两个双精度数的小于关系
private
bool
Small(
double
n1,
double
n2)

...
{
return n1 < n2;
}
//
两个双精度数的大于关系
private
bool
Big(
double
n1,
double
n2)

...
{
return n1 > n2;
}

private
void
BtnSort_Click(
object
sender, EventArgs e)

...
{
if (RbBitSmall.Checked)
TxtRes.Text = Sort(TxtOrig.Text, BitSmallSort);
else if (RbBitBig.Checked)
TxtRes.Text = Sort(TxtOrig.Text, BitBigSort);
else if (Rbxiao.Checked)
TxtRes.Text = Sort(TxtOrig.Text, Small);
else if (RbDa.Checked)
TxtRes.Text = Sort(TxtOrig.Text, Big);
}
本文的源程序:
http://download1.csdn.net/down3/20070617/17135051171.rar
本文是作者原创,转载请注明出处,谢谢。