【问题标题】:Using void return types with new Func<T, TResult>使用带有 new Func<T, TResult> 的 void 返回类型
【发布时间】:2010-11-22 10:18:57
【问题描述】:

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

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

委托看起来像这样:

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

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

public static void OtherFunction(int a, string b) { ... }
var del = new Func<int, string, void>(OtherFunction);

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    如果没有返回类型,你要Action&lt;int,string&gt;:

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

    或者只是:

    Action<int, string> del = OtherFunction;
    

    【讨论】:

      【解决方案2】:

      要返回void,必须使用Action

      【讨论】:

        【解决方案3】:

        如果你不想返回一些东西,你需要 Action

        【讨论】:

          【解决方案4】:

          如果您不需要任何返回值,请使用 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();
                      }
                  }
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2010-10-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多