Action
系统封装的Action委托,没有参数没有返回值。调用实例为:
class Program
{
public delegate void Action();
static void Main(string[] args)
{
Action action = new Action(Method);
action();
}
private static void Method()
{
Console.WriteLine("i am is a action");
}
}
如果方法的表达很简单,可以使用Lambda表达式,代码如下:
Action action = () => { Console.WriteLine("i am is a action"); };
action();
Action<T>
系统封装的Action<T>委托,有参数但是没有返回值。调用实例为:
class Program
{
public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
static void Main(string[] args)
{
Action<int,int> action = new Action<int,int>(Method);
action(2,3);
}
private static void Method(int x,int y)
{
Console.WriteLine("i am is a action");
}
}
使用Lambda表达式编写Action<T>代码如下:
Action<int, int> action = (x, y) => { Console.WriteLine("i am is a action"); };
action(2,3);
Fun<T>
系统封装的Fun<T>委托,有参数而且返回值。调用实例为:
class Program
{
public delegate TResult Fun<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
static void Main(string[] args)
{
Fun<int, int, bool> fun = new Fun<int, int, bool>(Method);
bool ret = fun(2,3);
}
private static bool Method(int x,int y)
{
if (x + y == 5)
{
return true;
}
else
{
return false;
}
}
}
使用Lambda表达式编写Fun<T>,代码如下:
Fun<int, int, bool> fun = (x, y) =>
{
if (x + y == 5)
{
return true;
}
else
{
return false;
}
};
bool ret = fun(2,3);