// The following is an example of Predicate :// a functional interface that takes an argument// and returns a boolean primitive type.
Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.boolean result = pred.test(4); // true
public Int32 Add(Int32 a, Int32 b){return a + b;}
public Int32 Sub(Int32 a, Int32 b){return a - b;}
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op){Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));}
public void Test(){Calculator(10, 23, Add);Calculator(10, 23, Sub);}
这调用计算器,不仅传递两个数字,还传递在计算器中调用哪个方法以获取计算结果。
在C#2.0中,我们得到了匿名方法,它将上述代码缩短为:
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op){Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));}
public void Test(){Calculator(10, 23, delegate(Int32 a, Int32 b){return a + b;});Calculator(10, 23, delegate(Int32 a, Int32 b){return a - b;});}
然后在C#3.0中,我们得到了lambda,这使得代码更短:
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op){Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));}
public void Test(){Calculator(10, 23, (a, b) => a + b);Calculator(10, 23, (a, b) => a - b);}
def name_of_func():#command/instructionprint('hello')
print(type(name_of_func)) #the name of the function is a reference#the reference contains a function Object with command/instruction