委托使用小结
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委托可带一个或多个参数
定义委托有以下几种方式:
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(); } }
相关文章推荐
- 关于c#中委托使用小结
- 异步编程(AsyncCallback委托,IAsyncResult接口,BeginInvoke方法,EndInvoke方法的使用小结)
- git使用小结
- 委托和事件的使用
- jstree使用小结(一)
- Excel VBA利用ADODB访问数据库使用小结
- shell 中find和xargs命令使用小结
- Soursight Insight 使用小结
- tomcat结合nginx使用小结
- github使用小结--本地建库并同步到github
- NIO使用小结
- 使用DataSource小结
- Android菜鸟的成长笔记——Android Studio使用小结
- 简单的委托使用
- iOS开发小结 - 使用自定义字体
- C#中使用委托
- OrmLite使用小结(一)
- Volley使用小结
- tomcat结合nginx使用小结
- GLSL(4)关于layout和uniform使用的个人小结