2010-11-05 36 views
1

有誰知道如何爲Func和Action指針聲明源代碼?我試圖理解使用委託進行異步調用的理論以及與線程綁定的方式。Func <>和原始代碼

例如,如果我有代碼如下:

static void Main() 
{ 
    Func<string, int> method = Work; 
    IAsyncResult cookie = method.BeginInvoke ("test", null, null); 
    // 
    // ... here's where we can do other work in parallel... 
    // 
    int result = method.EndInvoke (cookie); 
    Console.WriteLine ("String length is: " + result); 
} 

static int Work (string s) { return s.Length; } 

我將如何使用「委託」型替換函數功能<>結構;我想弄明白的原因是因爲Func只能接受一個輸入和一個返回變量。它不允許它指向的方法具有設計靈活性。

謝謝!

回答

2

Func<int, string>只是一個普通的委託。它只是幫助您避免編寫常見的代表。而已。如果它不適合你,應該寫你自己的delagate。 代替你都在問一個delagate是

delegate string Method(int parm); 

,如果你想有一個FUNC(用於istance),其採用22 :-)整數,並返回你有一個字符串來寫你自己的委託

delegate string CrazyMethod(int parm1,int parm2,.....) 

在你的情況

delegate int MyOwnDeletage(string d); 
    class Program 
    { 

     static int Work(string s) { return s.Length; } 

     static void Main(string[] args) 
     { 

      // Func<string, int> method = Work; 
      MyOwnDeletage method =Work; 

       IAsyncResult cookie = method.BeginInvoke ("test", null, null); 
       // 
       // ... here's where we can do other work in parallel... 
       // 
       int result = method.EndInvoke (cookie); 
       Console.WriteLine ("String length is: " + result); 
     } 
    } 
+0

我將如何替換上面的代碼中的這個實例化,以便我可以調用beginInvoke()方法並將其指向Work()方法? – locoboy 2010-11-05 10:43:18

+0

看看我編輯過的文章。我可以在這裏回答,因爲我必須發佈代碼 – 2010-11-05 13:26:09

+0

謝謝,這是我尋找的答案 – locoboy 2010-11-06 10:58:04

5

Func<T>沒什麼特別的,真的。這是簡單的:

public delegate T Func<T>(); 

事實上,以支持不同數量的參數,也有一羣人宣,如:

public delegate void Action(); 
public delegate void Action<T>(T arg); 
public delegate U Func<T, U>(T arg); 
// so on... 
+0

小點 - OP使用:'委託TResult Func鍵(T ARG);' – 2010-11-05 10:18:04

+0

對不起,我有點失落。您能否在聲明中提供更多信息?當我說「Func method = Work;」時,如果你可以在代碼中幫助我,可能會更清楚。我怎樣才能使用'委託'關鍵字來替換該細分受衆羣? – locoboy 2010-11-05 10:39:25

+0

@ cfarm54:我可能錯誤地理解了你的問題。如果你想知道定義匿名方法的語法,它將是:'Func method = delegate(string s){return s.Length; };'。當然,你可以使用lambda語法並且更加簡潔:'Func method = s => s.Length;'。指出匿名方法決不侷限於'Func'和'Action'代表是很重要的。他們可以使用任何符合其簽名的委託類型。 – 2010-11-05 23:25:01

相關問題