c#-委托
来源:互联网 发布:php文件上传大小限制 编辑:程序博客网 时间:2024/05/16 23:45
c#委托
委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。
委托就是相当于c++中的指针。
总的来说委托就是方法里面还有方法!
步骤:1.定义一个委托,类型和参数;
2.用于委托的方法,类型和参数与委托保持一致;
3.调用委托;
实例一:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delegateDemo
{
public delegate void callDelegate(int a, int b);
class Program
{
//定义一个委托
private static void big(int a, int b)
{
if (a > b)
Console.WriteLine("a"+a);
else
Console.WriteLine("a"+b);
}
private static void small(int a, int b)
{
if (a < b)
Console.WriteLine(a);
else
Console.WriteLine(b);
}
//在函数内使用委托
private static void Process(int a, int b, callDelegate call)
{
call(a, b);
}
static void Main(string[] args)
{
//委托实例与方法相关联
Process(10, 20,big);
Process(10, 20,small);
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delegateDemo
{
public delegate void callDelegate(int a, int b);
class Program
{
//定义一个委托
private static void big(int a, int b)
{
if (a > b)
Console.WriteLine("a"+a);
else
Console.WriteLine("a"+b);
}
private static void small(int a, int b)
{
if (a < b)
Console.WriteLine(a);
else
Console.WriteLine(b);
}
//在函数内使用委托
private static void Process(int a, int b, callDelegate call)
{
call(a, b);
}
static void Main(string[] args)
{
//委托实例与方法相关联
Process(10, 20,big);
Process(10, 20,small);
Console.ReadKey();
}
}
}
实例二:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delegateDemo
{
public class ab
{
//用于委托调用的方法
public int Big(int a, int b)
{
if (a > b)
return a;
else
return b;
}
public int Small(int a, int b)
{
if (a < b)
return a;
else
return b;
}
}
class Program
{
//定义一个委托
public delegate int callDelegate( int a, int b);
//在函数内使用委托
public static int Process( int a, int b, callDelegate call)
{
return call(a, b);
}
static void Main(string[] args)
{
//委托实例与方法相关联
callDelegate delegateBig=new callDelegate( new ab().Big);
int big = delegateBig(10, 20);
//用委托调用相关联的方法
int small = Process(10, 20, new callDelegate( new ab ().Small));
Console.WriteLine(big);
Console.WriteLine(small);
}
}
}
0 0
- C#- 委托
- C#- 委托
- c#-委托
- C#---委托
- C#委托
- C#--委托
- C#中的委托
- C#中的委托
- 天天学C#--委托
- C#中的委托
- C#中的委托
- C#中的委托
- C#-委托(delegate)
- C#中的委托
- c#·委托&事件
- C#-委托(delegate)
- C#中的委托
- C#中的委托
- c#中的命名空间
- ZOJ 2671 Cryptography(矩阵线段树)
- Algorithms—33.Search in Rotated Sorted Array
- SQL语句基础优化
- PayPal高级工程总监:读完这100篇论文 就能成大数据高手
- c#-委托
- android学习路线 1.1 Android应用开发揭秘 所学之对已用处
- C# WPF如何使用多线程
- IOS内存管理retain,assign,copy,strong,weak
- Contains Duplicate
- 互联网笔试面试专题
- Chrome应用技巧之颜色拾取
- Spring MVC @RequestBody接收JSON报HTTP 415/400问题的解决
- linux下vi命令大全