delegate bool Filter(string s);
class test
{
static void Main()
{
Filter f=new Filter(A);
Display(new string[]{"ant","line","yok"},f);
}
static bool A(string s)
{
return "N".CompareTo(s)>;
}
static void Display(string[] Names,Filter f)
{
int count=;
foreach(string str in Names)
if(f(str))
console.writeline("Item {0} is {1}",count++,str);
}
}
2.组播委托
delegate void methodinvoker();
class test
{
static void Main()
{
new test();
}
test()
{
methodinvoker m=null;
m+=new methodinvoker(Foo);
m+=new methodinvoker(Goo);
m();
}
void Foo()
{
console.writeline("Foo");
}
void Goo()
{
console.writeline("Goo");
}
}
委托能处理的事情接口也能同样处理
interface IFilter
{
bool Filter(string s);
}
class test
{
class A:IFilter
{
public bool Filter(string s)
{
return "N".CompareTO(s)>;
}
static void Main()
{
A a=new A();
Display(new string[]{"ant","lion","yok"},IFilter f);
}
static void Display(string[] Names,IFilter f)
{
int count=;
foreach(string s in Names)
if(f(s))
console.writeline("Item {0} is {1}",count++,s);
}
}
}
注:委托处理虽然根漂亮,但委托最好用在事件上。