您的位置:首页 > 其它

委托使用小结

2015-05-28 00:22 309 查看
委托:一种定义方法签名的类型。通过委托指向一个方法,实现方法的异步调用。

定义委托有以下几种方式:

1.delegate

public
class MathsOp

{

public static int
calutlate (int x,int y)

{

return x+y;

}

}

[STAThread]

static void Main(string[] args)

{

public
delegate int myDelegate(int j,int k);

myDelegate operation= new myDelegate( MathsOp.calutlate);//创建委托时,签名的方法参数要与定义的委托参数一致

int result = operation(1,3);//异步调用方法

}

2、Action

Action 主要用来定义无返回值的委托

(1) 无参数,无返回值委托

Action action = new Action(() =>

{

//执行代码

}
//指定当前委托的回调参数
action.BeginInvoke(new AsyncCallback((result) =>

{

ImportComplete(result.IsCompleted);

}), null);

public void ImportComplete(bool

IsCompleted){

//委托方法执行完后回调函数执行代码

}

(2)无返回值,带参数委托
如Action<int,string>
表示有传入参数int,string无返回值的委托

3
Func

Func是有返回值的泛型委托,

Func<int> 表示无参,返回值为int的委托

Func<object,string,int> 表示传入参数为object, string 返回值为int的委托,Func委托可带一个或多个参数
public class GenericFunc
{
public static void Main()
{
// Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";
Console.WriteLine(convertMethod(name));
}

private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: