C#中的委托

C#中的委托

引言:C#中的委托着实让我迷惑(我是位初学者),在不同的C#书籍中,还译为代理、委派等,经反复查阅资料和自己动手编写代码,才稍稍理出点头绪。

C# 中的委托类似于 C 或 C++ 中的函数指针 , 但两者有本质区别: C 或 C++ 不是类型安全的,但 C# 中的委托是面向对象的,而且是类型安全的。

从技术角度来讲,委托是一个引用类型,用来封装带有特定签名和返回类型的方法。

1 、声明委托

C# 使用关键字 delegate 来声明委托类型:

[ 访问修饰符 ] delegate 结果类型 委托标识符( [ 形参列表 ] );

委托类型可以在声明类的任何地方声明。

2 、实例化委托

委托使用 new 运算符来实例化。

新创建的委托实例所引用的对象为以下之一:

⑴委托创建表达式中引用的静态方法

⑵委托创建表达式中引用的目标对象(此对象不能为 null )和实例方法

⑶另一个委托

例如:

delegate void MyDelegate( int x);

class MyClass

{

public static void Method1( int i)

{

}

public void Method2( int i)

{

}

}

class TestClass

{

static void Main ()

{

// 静态方法

MyDelegate delegate1= new MyDelegate(MyClass.Method1);

// 实例方法

TestClass class1= new MyClass();

MyDelegate delegate2= new MyDelegate(MyClass.Method2);

// 另一个委托

MyDelegate delegate3= new MyDelegate(delegate2);

}

}

3 、使用委托

通过委托对象的名称及放入括号的要传递给委托的参数来调用委托对象。调用委托时,调用表达式的主表达式必须是委托类型的值

以下是我写的一个例子:

namespace delegateTest

{

public delegate int mydelegateTest( int i, int j);

class calculate

{

public static int add( int i, int j)

{

return i+j;

}

public static int minus( int i, int j)

{

return i-j;

}

}

class delegateapp

{

static void Main ( string [] args)

{

mydelegateTest d0= new mydelegateTest(calculate.add); // 声明一个 mydelegateTest 的实例 d0 ,并用 calculate.add 对其进行初始化,实际上就是将委托与方法链接起来。

int i=d0(99,1); // 开始调用委托,就像是使用静态成员方法 calculate.add(int i,int j) 一样。

System.Console.WriteLine(" 这是运行 add 的结果 :{0}",i);

mydelegateTest d1= new mydelegateTest(calculate.minus);

int j=d1(100,99);

System.Console.WriteLine(" 这是运行 minus 的结果 :{0}",j);

System.Console.ReadLine();

}

}

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus