课本上关于委托的一个小问题,请各位高手指导一下
using System;public class SortClass
{
static public int val1;
static public int val2;
public delegate void Sort(ref int a,ref int b);//定义一个委托
public void DoSort(Sort ar)//接受委托对象的方法,执行被委托的方法
{
ar(ref val1,ref val2);
}
}
public class SortProgram //定义两种方法
{
public static void Ascending(ref int first,ref int second)
{
if(first>second)
{
int tem=first;
first=second;
second=tem;
}
}
public static void Descending(ref int first,ref int second)
{
if(first<second)
{
int tem=first;
first=second;
second=tem;
}
}
public static void Main() //主程序入口
{
SortClass.Sort up=new SortClass.Sort(Ascending);//方法与委托关联
SortClass.Sort down=new SortClass.Sort(Descending);//代表对象up和down
SortClass dolT=new SortClass();
SortClass.val1=310;
SortClass.val2=220;
Console.WriteLine("Before Sort:val1={0},val2={1}",SortClass.val1,SortClass.val2);
dolT.DoSort(up);
Console.WriteLine("After Sort:val1={0},val2={1}",SortClass.val1,SortClass.val2);
Console.WriteLine("Before Sort:val1={0},val2={1}",SortClass.val1,SortClass.val2);
dolT.DoSort(down);
Console.WriteLine("After Sort:val1={0},val2={1}",SortClass.val1,SortClass.val2);
}
}
编译的时候,出现了两处错误:
(1)非静态字段、方法或属性“ConsoleApplication1.SortProgram.Ascending(ref int,ref int)”要求对象引用.
(2)非静态字段、方法或属性“ConsoleApplication1.SortProgram.Descending(ref int,ref int)”要求对象引用.
为什么会出现这两处错误,请各位高手不要吝啬,多多指教!