开发者

Func<> and primitive code

Does anyone know how the source code is declared for the Func and Action pointers? I'm trying to understand the theory behind making an asynchronous call using delegates and how that is tied to threading.

For example, if I have the code below:

    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...
  开发者_C百科//
  int result = method.EndInvoke (cookie);
  Console.WriteLine ("String length is: " + result);
}

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

How would I use the 'delegate' type to replace the Func<> structure; the reason I'd like to figure it out is because Func can only take an input and a return variable. It doesn't allow for design flexibility in the method that it's pointing to.

Thanks!


Func<T> is nothing special, really. It's simply:

public delegate T Func<T>();

In fact, to support different number of arguments, there are a bunch of them declared, like:

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


Func<int, string> is just a generic delegate. It just helps you avoid writing common delegates. That's it. If it doesn't fit for you should write your own delagate. the delagate to replace the one you are asking is

delegate string Method(int parm);

if you want a func(for istance) that takes 22 :-) integer and return a string you have to write you own delegate

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

In your case

 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜