2010-11-05 38 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

相关问题