C# delegate ,Action,Func
delegate传统的委托,无泛型概念。
namespace ConsoleApplication1
{
class Program
{
private delegate bool Mydel(int a, int b);
private static bool OneFun(int a, int b)
{
Console.WriteLine("a={0},b={1}", a, b);
return a > b;
}
static void Main(string[] args)
{
Mydel C = new Mydel(OneFun);
C(1, 2);
Console.ReadLine();
}
}
}
Action,
Action(Of T) 委托
封装一个方法,该方法只有一个参数并且不返回值。
理解:也是委托,输入参数为泛型,可以多达16个输入参数(in),返回值都必须为空。
public delegate void Action<in T1>
public delegate void Action<in T1,in T2>
...
....
public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6>
namespace ConsoleApplication1
{
class Program
{
private delegate bool Mydel(int a, int b);
private static void OneFun(int a, string b,int c,object d)
{
Console.WriteLine("im here");
return;
}
static void Main(string[] args)
{
Action<int, string, int, object> MyAction = OneFun;
OneFun(1,"ok",4,5);
Console.ReadLine();
}
}
}
Func
Func<T, TResult> 委托
封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
理解:也是委托,输入参数为泛型,只是一个返回值,可多达0~16个输入参数。
delegte Func<out TResult>
delegte Func<in T1,out TResult>
delegte Func<in T1,in T2,out TResult>
...
....
delegte Func<in T1,in T2,in T3,in T4,out TResult>
namespace ConsoleApplication1
{
class Program
{
private static int OneFun(int a, string b,int c,object d)
{
Console.WriteLine("im here");
return 2;
}
private static int fun()
{
Console.WriteLine("im here2");
return 1;
}
static void Main(string[] args)
{
Func<int> MyFunc = new Func<int>(fun);
MyFunc();
Func<int, string, int, object, int> MyFunc2 = new Func<int, string, int, object, int>(OneFun);
OneFun(1,"jkjkj",3,4);
Console.ReadLine();
}
}
}
posted on 2013-04-04 14:45 Shine-Zhong 阅读(241) 评论(0) 编辑 收藏 举报