Func委托意外地工作

meo*_*nge 0 c# linq extension-methods functional-programming

我有一个IEnumerable接口的扩展方法,它接受一个类型的委托Func<T, bool?>作为参数:

 public static bool? ForEach<T>(this IEnumerable<T> source, Func<T, bool?> func)
 {
        bool? commandSuccessful = true;

        foreach (var element in source)
        {
            var rv = func(element);

            if (rv == null)
            {
                return null;
            }

            if (rv == false)
            {
                commandSuccessful = false;
            }
        }

        return commandSuccessful;
  }
Run Code Online (Sandbox Code Playgroud)

但是当func的签名是Func <T, RuntimeDetails, bool?>:时,仍然可以使用相同的扩展方法:

RuntimeDetails lastRuntimeDetails = null;
var startCommandSuccessful = 
    activeConfiguration.Applications.ForEach( 
                        _ => PrepareRuntimeDetailsAndDownload( _ , ref lastRuntimeDetails));



private bool? PrepareRuntimeDetailsAndDownload(Application configurationApplication, 
            ref RuntimeDetails lastRuntimeDetails)
        {...}
Run Code Online (Sandbox Code Playgroud)

我同时感到困惑和快乐.它为什么有效?如果它不起作用,我不知道如何编写扩展名,因为RuntimeDetails扩展方法中的参数是未知的.

Ren*_*ogt 6

你的假设是错误的

_ => PrepareRuntimDetailsAndDownload(...)
Run Code Online (Sandbox Code Playgroud)

是不是一个Func<T, RunTimeDetails, bool?>!它一个Func<T, bool?>,它需要一个类型的参数T并返回一个bool?.你没有lastRuntimeDetails作为参数传递.这只是一个关闭.