你可以這樣做一個lambda expression:
public static void SomeMethod() {
int x = 0;
Action bob =() => {x += 2;};
bob();
x += 1;
bob();
Console.WriteLine(x); //print (will be 5)
}
Lambda表達式如下部分() => {x += 2;}
。 ()
表示該動作根本不輸入任何內容。在讚美之間,你可以指定應該執行的語句。在lambda表達式左側未定義的變量(如x
)與C/C++/Java語言系列中的正常範圍規則有界。這裏x
因此與SomeMethod
中的局部變量x
綁定。
Action
是delegate
,它指的是一個「方法」,你可以把它稱爲高階方法。
請注意,您的代碼不是C#。你不能寫int main
作爲主要方法。
演示(Mono的C#交互的shell csharp
)
$ csharp
Mono C# Shell, type "help;" for help
Enter statements below.
csharp> public static class Foo {
>
> public static void SomeMethod() {
> int x = 0;
> Action bob =() => {x += 2;};
> bob();
> x += 1;
> bob();
> Console.WriteLine(x);
> }
>
> }
csharp> Foo.SomeMethod();
5
@Tim該代碼甚至不會編譯。 – juharr
你可以用lambda表達式來做到這一點。 –
'int main()'?這在C#中是無效的... –