مروری بر کاربردهای Action و Func - قسمت اول
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۵/۲۵ ۱۳:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
namespace ActionFuncSamples
{
public delegate int AddMethodDelegate(int a);
public class DelegateSample
{
public void UseDelegate(AddMethodDelegate addMethod)
{
Console.WriteLine(addMethod(5));
}
}
public class Helper
{
public int CustomAdd(int a)
{
return ++a;
}
}
class Program
{
static void Main(string[] args)
{
Helper helper = new Helper();
// .NET 1
AddMethodDelegate addMethod = new AddMethodDelegate(helper.CustomAdd);
new DelegateSample().UseDelegate(addMethod);
// .NET 2, anonymous delegates
new DelegateSample().UseDelegate(delegate(int a) { return helper.CustomAdd(a); });
// .NET 3.5
new DelegateSample().UseDelegate(a => helper.CustomAdd(a));
}
}
}
Action<int> example1 = x => Console.WriteLine("Write {0}", x);
example1(5);
Func<int, string> example2 = x => string.Format("{0:n0}", x);
Console.WriteLine(example2(5000));
using System;
namespace ActionFuncSamples
{
public interface ISchedule
{
void Run();
}
public class Runner
{
public void Exceute(ISchedule schedule)
{
schedule.Run();
}
}
public class HelloSchedule : ISchedule
{
public void Run()
{
Console.WriteLine("Just Run!");
}
}
class Program
{
static void Main(string[] args)
{
new Runner().Exceute(new HelloSchedule());
}
}
}
using System;
namespace ActionFuncSamples
{
public class Schedule
{
public void Exceute(Action run)
{
run();
}
}
class Program
{
static void Main(string[] args)
{
new Schedule().Exceute(() => Console.WriteLine("Just Run!"));
}
}
}
Func<string, int> parse = (string s) => int.Parse(s);
var parse = (string s) => int.Parse(s);
var upper = (s) => s.ToUpperInvariant();
var createException = (bool b) => b ? new ArgumentNullException() : new DivideByZeroException();
var createException = Exception (bool b) => b ? new ArgumentNullException() : new DivideByZeroException();
var oneTwoThreeArray = () => new[]{1, 2, 3}; // inferred type is Func<int[]>
var oneTwoThreeList = IList<int> () => new[]{1, 2, 3}; // same body, but inferred type is now Func<IList<int>> Func<int> read = Console.Read; Action<string> write = Console.Write;
var read = Console.Read; // Just one overload; Func<int> inferred var write = Console.Write; // ERROR: Multiple overloads, can't choose
var choose = [Example(2)][Example(3)] object (bool b) => b ? 1 : "two";
Action<int,int,int> ac;
public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2); public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
Func<(string firstName, string lastName), string> f = (data) => data.firstName + data.lastName;
f(("Foo", "Bar"));