C#委托之Action与Func用法
一、Action,可以传入参数,没有返回值的委托
1、调用方法
static void Main(string[] args)
{
Action<int, int> addcalc = new Action<int, int>(AddCalc);
addcalc(2, 3);
Console.ReadKey();
}
static void AddCalc(int x, int y)
{
Console.WriteLine(x + y);
}
2、使用lambda表示式
static void Main(string[] args)
{
Action<int, int> addcalc = ((x, y) => Console.WriteLine(x+y));
addcalc(2, 3);
Console.ReadKey();
}
3、作为参数传
static void Main(string[] args)
{
Action<string> a1 = (p => Console.WriteLine("方法一,参数值:" + p));
Action<string> a2 = (p => Console.WriteLine("方法二,参数值:" + p));
AddCalc(a1, "输入参数1");//调用AddCalc方法,传入委托作为参数
AddCalc(a2, "输入参数2");
Console.ReadKey();
}
static void AddCalc<T>(Action<T> action,T inputParam)
{
action(inputParam);
}
二、Func,可以传入参数,必须有返回值的委托
1、调用方法
static void Main(string[] args)
{
Func<string> f = new Func<string>(ShowMessage);
string result = f();//调用委托。
Console.ReadKey();
}
static string ShowMessage()
{
return "welcome to zhengzhou";
}
2、使用lambda表达式
static void Main(string[] args)
{
////实例化一个委托,注意不加大括号,写的值就是返回值,不能带return
Func<string> f1 = () => "welcome to delegate world";
//实例化另一个委托,注意加大括号后可以写多行代码,但是必须带return
Func<string> f2 = () =>
{
return "Welcome to delegate world";
};
Func<string, string> f3 = x => x.ToUpper();
string result1 = f1();//调用委托
string result2 = f2();
string result3 = f3("abc");
Console.ReadKey();
}
3、作为参数传递
static void Main(string[] args)
{
//实例化一个委托,注意不加大括号,写的值就是返回值,不能带return
Func<int, string> fc1 = (p) => string.Format("传入了参数{0}", p);
//实例化另一个委托,注意加大括号后可以写多行代码,但是必须带return
Func<string, string> fc2 = (p) =>
{
return string.Format("传入了参数{0}", p);
};
string result = Transfer<int>(fc1, 1);//调用委托
string result2 = Transfer<string>(fc2,"hello");
Console.ReadKey();
}
static string Transfer<T>(Func<T, string> func, T inputParam)
{
return func(inputParam);
}
三、Predicate一个传入参数,返回一个bool类型的值
class Program
{
static Predicate<int> myPredicate;
static int[] myNum = new int[8] { 12, 33, 89, 21, 15, 29, 40, 52 };
public static int[] myResult;
static void Main(string[] args)
{
myPredicate = delegate(int curNum)
{
if (curNum % 2 == 0) return true;
else return false;
};
myResult = Array.FindAll(myNum, myPredicate);
for (int i = 0; i < myResult.Length; i++)
{
Console.WriteLine(myResult[i]);
}
}
}