代码之家  ›  专栏  ›  技术社区  ›  Greg

将void返回类型与new Func<T,TResult>

  •  25
  • Greg  · 技术社区  · 14 年前

    我在代码中使用匿名委托调用以下示例函数:

    public static int TestFunction(int a, int b) {
        return a + b;
    }
    

    代理如下所示:

    var del = new Func<int, int, int>(TestFunction);
    

    我的问题是:如何指定 void 返回类型 TResult ? 以下操作不起作用:

    public static void OtherFunction(int a, string b) { ... }
    var del = new Func<int, string, void>(OtherFunction);
    
    4 回复  |  直到 14 年前
        1
  •  44
  •   Marc Gravell    14 年前

    如果没有返回类型,则需要 Action<int,string> :

    var del = new Action<int, string>(OtherFunction);
    

    或者只是:

    Action<int, string> del = OtherFunction;
    
        2
  •  7
  •   Simone    14 年前

    如果要返回void,必须使用Action<T>。

        3
  •  3
  •   TalentTuner    14 年前

    如果不想退货,您需要采取措施

        4
  •  0
  •   Pradeep Mishra    9 年前

    如果不需要任何返回值,请使用Action而不是Func

        public void InvokeService<T>(Binding binding, string endpointAddress, Action<T> invokeHandler) where T : class
        {
            T channel = FactoryManager.CreateChannel<T>(binding, endpointAddress);
            ICommunicationObject communicationObject = (ICommunicationObject)channel;
    
            try
            {
                invokeHandler(channel);
            }
            finally
            {
                try
                {
                    if (communicationObject.State != CommunicationState.Faulted)
                    {
                        communicationObject.Close();
                    }
                }
                catch
                {
                    communicationObject.Abort();
                }
            }
        }