C# 3.0ããã©ã ãå¼ãä½æåºæ¥ãããã«ãªãã¾ãããpythonã使ã£ã¦ãã人ã«ã¯
ããªãã¿ã®ãã®ã§ããã
ã¡ãªã¿ã«pythonã®å ´åã¯ã以ä¸ã®ããã«ãã¦ã©ã ãå¼ãä½æãã¾ãã
f = lambda x: x * x f(2)
åããã®ãC#ã§æ¸ãã¨ä»¥ä¸ã®ããã«ãªãã¾ãã
Func<int, int> f = x => { return x * x; }; Console.WriteLine(f(2));
ä¸è¨ã®é¨åã§
x => { return x * x; };
ã¨ãªã£ã¦ããé¨åãã©ã ãå¼ã§ããC# 2.0ã®å ´åã¯ä»¥ä¸ã®ããã«è¨è¿°ãã¦ãã¾ããã
Func<int, int> f = delegate(int x){ return x * x; }; Console.WriteLine(f(2));
ã©ã ãå¼ã¯ãå¿åããªã²ã¼ããããå°ã簡便ã«è¨è¿°ã§ããããã«ãªã£ãã¨ããé°å²æ°ã ã¨
æãã¨åãããããã§ãããªã®ã§ãArray.ForEachãªã©ãæ¸ãããããªãã¾ãã
Array.ForEach(Array.ConvertAll(new[]{"hoge", "hehe", "fuga"}, elem => { return elem.ToUpper(); }), elem => { Console.WriteLine(elem); });
ä¸ã®ä¾ã¯å¿åããªã²ã¼ãã使ç¨ãã¦ãåããã®ãè¨è¿°ã§ãã¾ãããã©ã ãå¼ã§è¨è¿°ããã»ããå人çã«ã¯è¦ãããã§ãã
ã¾ããã©ã ãå¼ãå©ç¨ãããã¨ã§ã¯ãã¼ã¸ã£ã¼(Closure)ãæ¸ããã¨ãåºæ¥ã¾ãã(å¿åããªã²ã¼ãã§ãåºæ¥ã¾ããã»ã»)
Func<int, Func<int, int>> MakeClosure = x => { return y => { return x + y; }; }; Func<int, int> closure = MakeClosure(10); Func<int, int> closure2 = MakeClosure(20); Console.WriteLine(closure(100)); Console.WriteLine(closure2(100));
ä¸è¨ãå®è¡ããã¨ã110, 120ã¨ãªãã¾ãã
ã¡ããã¨ã¯ãã¼ã¸ã£ã¼ãä½æããéã«æ¸¡ããæ¬æ¥ãªãã¹ã³ã¼ãå¤ã®å¤ãä¿æããã¦ãã¾ããã(é¢æ°éå
)
ã¦ãã¨ã§ã以ä¸ãµã³ãã«ã§ãã
// vim:set ts=4 sw=4 et ws is nowrap ft=cs: using System; namespace Gsf.Samples.Tmp{ public class LambdaExpressionSample : IExecutor{ public void Execute(){ // // æ®éã«ã©ã ãå¼ãä½æ. // Func<int, int> f = x => { return x * x; }; Console.WriteLine(f(2)); // // Array.ForEachã¨Array.ConvertAllã®ããªã²ã¼ãã«ã©ã ãå¼ãæå®. // Array.ForEach(Array.ConvertAll(new[]{"hoge", "hehe", "fuga"}, elem => { return elem.ToUpper(); }), elem => { Console.WriteLine(elem); }); // // ã¯ãã¼ã¸ã£ã¼ãä½æ. // Func<int, Func<int, int>> MakeClosure = x => { return y => { return x + y; }; }; Func<int, int> closure = MakeClosure(10); Func<int, int> closure2 = MakeClosure(20); Console.WriteLine(closure(100)); Console.WriteLine(closure2(100)); } } }
ã¡ãªã¿ã«ãã©ã ãå¼ãå¿åããªã²ã¼ãã§ã¯ä¸æ¦ä½æããããªã²ã¼ããä¿æãã¦ããéã«
以ä¸ã®ã¸ã§ããªãã¯ããªã²ã¼ããè¯ã使ããã¾ãã
- System.Func
- System.Func
- System.Action
- System.Action(T)
- System.Predicate(T)
ä¸è¨ã®å
ãFuncã¸ã§ããªãã¯ããªã²ã¼ãã¯.NET Framework 3.5ã§ç»å ´ãã¾ããã
System.Core.dllå
ã«åå¨ãã¦ãã¾ãã
ã¾ããFunc,Actionããªã²ã¼ãã¯å
±ã«ãå¼æ°ãï¼ã¤ã¾ã§åãåãããã
è¤æ°å®ç¾©ããã¦ãã¾ãã