使用delegate的時候很多時候沒必要使用乙個普通的方法,因為這個方法只有這個delegate會用,並且只用一次,這時候使用匿名方法最合適。
匿名方法就是沒有名字的方法。
mydelegate p = delegate(int s) ;
在il中編譯器是給匿名方法生成了名字的
actiona1 = delegate(int i) ;
匿名方法最大的作用,是用來推導出lambda表示式
函式式程式設計,在entity framework程式設計中用的很多
*=>*讀作goes to
普通匿名型別也是一樣用lambda表示式//lambda表示式格式的匿名方法的寫法
action<
int> a2 =
(int i)
=>
; action<
int> a3 =
(i)=
>
;//如果只有乙個引數,可以不寫括號
action<
int> a4 = i =
>;a1
(6);
//funcf1 = delegate(string s, int i) ;
//funcf2 = (string s, int i) => ;
//funcf3 = (s, i) => ;
只有一行**且為返回值,可以省略方法體和return;
//funcf4 = (s, i) => true;
func<
int,
int> f1 =
delegate
(int i)
; func<
int,
int> f2 =
(int i)
=>
; func<
int,
int> f3 = i =
> i *2;
int j =f3(
5); console.
writeline
(j);
舉個栗子
展開和簡化都要有個過程,牢記。class program
;//int m = getmax(nums, compereint);
//1//funcf = delegate(int i1, int i2) ;
//int m = getmax(nums,f);
//2//int m = getmax(nums, delegate (int i1,int i2));
//3//int m = getmax(nums, (i1, i2) => );
person[
] persons = new person;
person p =
getmax
(persons,
(p1, p2)
=> p1.age > p2.age)
; console.
writeline
(p);
console.
readkey()
;}static bool compereint
(int i1,
int i2)
static t getmax
(t objs, func comperefunc)
return max;
} class person
public int age
public string name
public override string tostring()
}}
呼叫static class jiheext
}return resultlist;
}}
static
void
main
(string[
] args)
;//ienumerabler1 = nums.mywhere(i => i > 10);//delegate(int);
//ienumerabler1 = nums.mywhere(i => i%2==0);//delegate(int);
//foreach (int item in r1)
// string [
] nums = new string;
ienumerable r1 = nums.
mywhere
(s=>s.
contains
("老"))
;
foreach (string item in r1)
console.
readkey()
;}
Lambda表示式 匿名方法 委託
lambda表示式 匿名方法 委託 16 9 2017 代替匿名方法的簡單演示 using system using system.collections.generic using system.linq using system.text using system.threading.tasks...
匿名委託Lambda表示式
2種形式都是宣告委託的形式 2.0以前 c 命名方法是宣告委託的唯一方法 c 2.0 之後引入匿名方法 c 3.0以及更高版本中 使用lambda表示式 取代了匿名方法 作為編寫內聯 的首選方式 匿名方法 delegate void anonymity int x anonymity m anony...
匿名委託與Lambda表示式
通過使用匿名委託 匿名方法 使程式設計變得更加靈活,有關委託與匿名委託請參考我的前一篇blog 委託與匿名委託 繼續之前示例,如下 static void main string args worker worker new worker int result worker.handletwonum...