【问题标题】:Func<> and primitive codeFunc<> 和原始代码
【发布时间】:2010-11-05 10:15:07
【问题描述】:

有谁知道如何为 Func 和 Action 指针声明源代码?我正在尝试了解使用委托进行异步调用背后的理论以及它与线程的关系。

例如,如果我有以下代码:

    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; }

我将如何使用'delegate'类型来替换 Func 结构;我想弄清楚的原因是因为 Func 只能接受一个输入和一个返回变量。它不允许它所指向的方法具有设计灵活性。

谢谢!

【问题讨论】:

    标签: c# .net multithreading delegates


    【解决方案1】:

    Func&lt;T&gt; 没什么特别的,真的。很简单:

    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...
    

    【讨论】:

    • 小点 - OP正在使用:delegate TResult Func&lt;T, TResult&gt;(T arg);
    • 对不起,我有点迷路了。你能在声明中给我更多的信息吗?当我说“Func method = Work;”时,如果你能在代码中帮助我,也许会更清楚。我究竟如何使用“代表”关键字替换该段?
    • @cfarm54:我可能理解错了你的问题。如果你想知道定义匿名方法的语法,那就是:Func&lt;string, int&gt; method = delegate(string s) { return s.Length; };。当然,您可以使用 lambda 语法并且更简洁:Func&lt;string, int&gt; method = s =&gt; s.Length;。需要指出的是,匿名方法绝不限于FuncAction 委托。他们可以使用与其签名匹配的任何委托类型。
    【解决方案2】:

    Func&lt;int, string&gt; 只是一个通用委托。它只是帮助您避免编写常见的委托。就是这样。如果它不适合你应该写你自己的 delagate。 替换你所要求的那个的代表是

    delegate string Method(int parm);
    

    如果你想要一个 func(for 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); 
            }
        }
    

    【讨论】:

    • 如何替换上面代码中的这个实例化,以便调用 beginInvoke() 方法并将其指向 Work() 方法?
    • 看看我的帖子,我已经编辑过了。我可以在这里回答只是因为我必须发布代码
    • 谢谢,这是我一直在寻找的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2011-10-01
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多