2013-10-24 46 views
2

我在Windows Phone 7 C#示例中找到了以下方法。在這裏面你可以看到條款成功和方法內部使用失敗。我試過轉到定義與任一術語和Visual Studio沒有跳轉到任一術語的定義。我嘗試使用術語「動作」,「成功」,「失敗」,「C#」和「參數」搜索Google,但沒有發現任何有用的信息。 成功失敗在這個上下文宏或類似的東西?我在哪裏可以得到他們所做的解釋以及如何使用它們?請注意,工具提示幫助上空盤旋失敗顯示「參數動作<串>失敗」的時候。C#操作成功/失敗條款說明?

public void SendAsync(string userName, string message, Action success, Action<string> failure) 
    { 
     if (socket.Connected) { 

      var formattedMessage = string.Format("{0};{1};{2};{3};{4}", 
       SocketCommands.TEXT, this.DeviceNameAndId, userName, message, DateTime.Now); 

      var buffer = Encoding.UTF8.GetBytes(formattedMessage); 

      var args = new SocketAsyncEventArgs(); 
      args.RemoteEndPoint = this.IPEndPoint; 
      args.SetBuffer(buffer, 0, buffer.Length); 
      args.Completed += (__, e) => { 
       Deployment.Current.Dispatcher.BeginInvoke(() => { 
        if (e.SocketError != SocketError.Success) { 
         failure("Your message can't be sent."); 
        } 
        else { 
         success(); 
        } 
       }); 
      }; 
      socket.SendAsync(args); 
     } 
    } 
+2

http://msdn.microsoft.com/en-us/library/system.action.aspx – SLaks

+2

http://msdn.microsoft.com/en-us/library/ms173171.aspx – SLaks

回答

3

它們是被用作「回調函數」的委託。基本上,它們是提供給可以在該函數內部調用的另一個函數的函數。也許一個較小的樣本會更有意義:

static void PerformCheck(bool logic, Action ifTrue, Action ifFalse) 
{ 
    if (logic) 
     ifTrue(); // if logic is true, call the ifTrue delegate 
    else 
     ifFalse(); // if logic is false, call the ifFalse delegate 
} 

假印在下面的例子中,因爲1 == 2評估爲假。因此,logicPerformCheck方法中是錯誤的,所以它調用ifFalse委託。正如你所看到的,ifFalse打印到控制檯:

PerformCheck(1 == 2, 
      ifTrue:() => Console.WriteLine("Yep, its true"), 
      ifFalse:() => Console.WriteLine("Nope. False.")); 

而這一次將打印真正的..因爲1 == 1計算結果爲true。所以它調用ifTrue

PerformCheck(1 == 1, 
      ifTrue:() => Console.WriteLine("Yep, its true"), 
      ifFalse:() => Console.WriteLine("Nope. False.")); 
+0

瞭解,但其中是在回調中定義的匿名方法期間執行failure()或success()時執行的代碼?除了嘗試「轉到定義」的「成功」和「失敗」之外,我做了一個完整的解決方案搜索,找不到任何函數/方法等。定義爲「成功」或「失敗」。那麼當這些行動發生時會發生什麼? –

+1

他們是呼叫的一部分。轉到該方法的調用點(無論它在哪裏調用)並查看傳入的內容。如果它們直接放在方法體中,那很好。如果不是,他們將成爲代表,您可以「轉到定義」以查看其實施/分配。 –

+0

很好的例子。如果在這裏創建並擴展它在dotnetfiddle:https://dotnetfiddle.net/UhL3ua – GFoley83

2

可以爲持有其他方法變量想到Action(也Func)。

可以傳遞,分配,基本上做任何事情來的Action,你會任何其他變量,但你也可以這樣調用它的方法。

說你在你的代碼的方法有兩種:

public void Main(){ 
    Action doWork; 
    doWork = WorkMethod; 
    doWork(); 
} 

private void WorkMethod(){ 
    //do something here 
} 

分配WorkMethod的行動像你會做任何賦值給變量。然後,您可以像doWork一樣調用doWork。在這個例子中,它並不是特別有用,但你可能會看到標準變量的所有優點如何應用。

您在幾乎相同的方式使用ActionFunc。唯一真正的區別是Action代表void,而Func需要返回類型。

您也可以使用泛型。例如Action<int> respresents與簽名的方法

void methodName(int arg){}

Action<int, string>將是

void methodName(int arg1, string arg2){}

Func是類似的,Func<int>將是:

int methodName(){}

Func<string, int>是:

int methodName(string arg){}

重要的是要記住,最後鍵入Func定義是返回類型,即使它第一次出現在實際的方法簽名是很重要的。