New Feature #3: Lambda(λ) expressions
講這個之前呢,必須先知道有個delegates(委派)這東西。至於什麼是委派呢... 我也不是很清楚
= =,相當慚愧(orz) 所以才在上一篇貼了個文件XD。大概看得懂啦,不過不知道該怎麼寫。而且也還沒搞懂為什麼要這麼做(他存在的目的?)。
原本的delegates因為有了anonymous methods(匿名方法)而更簡潔。
現在要介紹的lambada expressions就是再進一步精簡他。
下面這個範例來自MSDN,裡面就包含了以具名、匿名,或這裡的重點,以lambda expression來 instantiate(實體化?) delegates:
1: // Declare delegate -- defines required signature:
2: delegate double MathAction(double num);
3:
4: class DelegateTest
5: {
6: // Regular method that matches signature:
7: static double Method4Delegates(double input)
8: {
9: return input * 2;
10: }
11:
12: static void Main()
13: {
14: // Instantiate delegate with named method(具名方法):
15: MathAction ma = Method4Delegates;
16:
17: // Invoke delegate ma:
18: double multByTwo = ma(4.5);
19: Console.WriteLine(multByTwo);
20:
21: // Instantiate delegate with anonymous method(匿名方法):
22: MathAction ma2 = delegate(double input)
23: {
24: return input * input;
25: };
26:
27: double square = ma2(5);
28: Console.WriteLine(square);
29:
30: // Instantiate delegate with lambda expression
31: MathAction ma3 = s => s * s * s;
32: double cube = ma3(4.375);
33:
34: Console.WriteLine(cube);
35: }
36: }
37:
New Feature #4: Extension methods
這個新功能也是個好東西,也一樣很難描述,所以一樣貼貼重點。
This new language feature makes it possible to treat existing types as if they were extended with additional methods.
In order to transform our method into an extension method, all we have to do is add the this keyword to the first parameter. The this keyword instructs the compiler to treat the method as an extension method.
小小看一下他的作用:
這裡有一小行code, 大概先把一堆processes做了些篩選,然後計算篩選出來的processes所佔用的memory, 最後做一個單位的換算。
BytesToMegaBytes(TotalMemory(FilterOutSomeProcesses(processes)));
嗯,對阿,然後呢? 然後如果把剛剛那些method變成extension method的話,就可以長成這樣:
processes
.FilterOutSomeProcesses()
.TotalMemory()
.BytesToMegaBytes();
上面那段code是為了方便閱讀才分成4行的,不是什麼特殊寫法XD。而且,看起來好像FilterOutSomeProcesses(), TotalMemory(), BytesToMegaBytes()就是processes的static method一樣,用個"."(dot)就可以叫用這些功能,他們其實是extension methods~ 酷吧~
但是!!! 以上面的code來說,如果processes其實也有一個instance method叫做TotalMemory呢? 在C#裡(VB.NET不太一樣), 如果extension method跟instance method都符合叫用條件的話,會優先呼叫該instance本身的method。
下面這個example就可以看出來:
1: using System;
2:
3: class Class1 {}
4: class Class2 {
5: public void Method1(string s) { Console.WriteLine("Class2.Method1");}
6: }
7: class Class3 {
8: public void Method1(object o) { Console.WriteLine("Class3.Method1");}
9: }
10: class Class4 {
11: public void Method1(int i) { Console.WriteLine("Class4.Method1");}
12: }
13: static class Extensions {
14: static public void Method1(this object o, int i)
15: {
16: Console.WriteLine("Extensions.Method1");
17: }
18:
19: static void Main()
20: {
21: new Class1().Method1(12);
22: new Class2().Method1(12);
23: new Class3().Method1(12);
24: new Class4().Method1(12);
25: }
26: }
27:
28: // Answer:
29: // Extensions.Method1
30: // Extensions.Method1
31: // Class3.Method1
32: // Class4.Method1
New Features #1, #2 請看c# 3.0 new features
Post a Comment