2015-06-01 24 views
2

我有一部分代碼在函數中多次重複。不過,我想做一個函數,但我想知道我的函數的變量,所以它可以修改它們而不需要通過它們(因爲有很多)。如何在C#中包含子函數的函數#

例如什麼我要完成

static void Main(string[] args) 
{ 
    int x = 0 

    subfunction bob() 
    { 
    x += 2; 
    } 

    bob(); 
    x += 1; 
    bob(); 
    // x would equal 5 here 
} 
+0

@Tim該代碼甚至不會編譯。 – juharr

+0

你可以用lambda表達式來做到這一點。 –

+0

'int main()'?這在C#中是無效的... –

回答

7

使用Action:使用

static void Main(string[] args) 
{ 
     int x = 0; 
     Action act =()=> { 
     x +=2; 
     }; 


     act(); 
     x += 1; 
     act(); 
     // x would equal 5 here 
     Console.WriteLine(x); 
} 
1

你可以這樣做一個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綁定。

Actiondelegate,它指的是一個「方法」,你可以把它稱爲高階方法。

請注意,您的代碼不是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 
+1

thx!也已經改變了int main – Cher

2

你可以換你的參數爲一類。

public class MyParams 
{ 
    public int X { get; set; } 
} 

public static void bob(MyParams p) 
{ 
    p.X += 2; 
} 

static void Main() 
{ 
    MyParams p = new MyParams { X = 0 }; 
    bob(p); 
    p.X += 1; 
    bob(p); 
    Console.WriteLine(p.X); 
} 

這大致是lambda回答在幕後做的。