C#之委托
1、首先,啥子是委托啊
顾名思义,委托就是一个SB啥都不会把自己的作业委托给班长来做,班长看着糟心也就帮SB做了,主要是为了避免被老师骂。
2、委托的定义
- 声明式定义
通过关键字delegate来进行定义
语法格式:修饰符 delegate 返回值类型 委托名称 (参数1,参数2,…)
//无返回值,无参数
delegate void SBInvoke();
//有返回值,有参数
delegate int JiSuanInvoke(int x,int y);
namespace ConsoleApplication3
{
delegate void SBInvoke();
class Program
{
static void Main(string[] args)
{
//将委托对象作为参数进行传递
SBInvoke method = SB.show;
mainMethod(method);
Console.ReadKey();
}
public static void mainMethod(SBInvoke sBInvoke)
{
//通过地址引用
IAsyncResult result = sBInvoke.BeginInvoke(null, sBInvoke);
sBInvoke.EndInvoke(result);
}
}
public class SB
{
//被引用的方法
public static void show()
{
Console.WriteLine("this is SB");
}
}
}
- 预定义
Action<in T1, in T2… in T6>只能委托引用一个返回值为 void 有参数或者没有参数的方法
tips:被引用方法返回值必须为空
namespace ConsoleApplication3
{
class Test
{
static void Main(string[] args)
{
Action action = actionMethod;
action();
Action<string> action2 = actionMethod2;
action2("world");
Console.ReadKey();
}
//无参Action
public static void actionMethod()
{
Console.WriteLine("hello");
}
//有参Action
public static void actionMethod2(string str)
{
Console.WriteLine("hello "+str);
}
}
}
Func<in T1, in T2… in T16, out TResult>引用的方法必须要有返回值,可以带0到16个参数
tips:被引用方法返回值必须要有(泛型最后一个参数是返回值类型)
namespace ConsoleApplication3
{
class Test
{
static void Main(string[] args)
{
Func<string> func = funcMethod;
Console.WriteLine( func());
Func<int, int, int> func2 = funcMethod2;
Console.WriteLine( func2(10, 30) );
Console.ReadKey();
}
//无参func
public static string funcMethod()
{
return "无参数的func";
}
//有参func
public static int funcMethod2(int a,int b)
{
return a + b;
}
}
}