zoukankan      html  css  js  c++  java
  • 公开的函数把函数作为參数

    公开的函数把函数作为參数

    假设想公开把其它的函数作为參数的函数。最好的方法是用托付(delegate)。

    考虑以下的样例。定义了两个函数,一个是公开函数,还有一个把函数公开为托付。

     

    module Strangelights.DemoModuleopen System

     

    /// a function that provides filtering

    let filterStringList f ra =

      ra |>Seq.filter f

     

    // another function that provides filtering

    let filterStringListDelegate (pred:Predicate<string>) ra =

      let f x =pred.Invoke(x)

      newResizeArray<string>(ra |> Seq.filter f)

     

    尽管,filterStringList 要比 filterStringListDelegate 短非常多,可是,库用户会感谢你为把函数公开为托付而付出的努力。当从 C# 中调用这个函数时,就能更加清晰地体会到为什么这样。

    以下的样例演示了调用filterStringList。

    调用这个函数。你须要创建托付,然后,使用FuncConvert 类把它转换成FastFunc,这是一种 F# 类型。用来表示函数值。对于库用户来说。另一件相当讨厌的事情,须要依赖于FSharp.Core.dll。而用户可能并不想用它。

    // !!! C# Source !!!

    using System;

    usingSystem.Collections.Generic;

    usingStrangelights;

    usingMicrosoft.FSharp.Core;

     

    class MapOneClass{

      public static void MapOne() {

        // define a list of names

       List<string> names = new List<string>(

          new string[] { "Stefany", "Oussama",

      "Sebastien", "Frederik"});

     

        // define a predicate delegate/function

       Converter<string, bool> pred =

          delegate(string s) {return s.StartsWith("S");};

     

        // convert to a FastFunc

       FastFunc<string, bool> ff =

          FuncConvert.ToFastFunc<string,bool>(pred);

     

        // call the F# demo function

       IEnumerable<string> results =

         DemoModule.filterStringList(ff, names);

     

        // write the results to the console

        foreach (var name inresults) {

         Console.WriteLine(name);

        }

      }

    }

     

    演示样例的执行结果例如以下:

    Stefany

    Sebastien

    如今。把它与调用filterStringListDelegate 函数进行对照,在以下的样例中展示。由于已经使用了托付,就能够使用 C# 的匿名托付功能,并把托付直接嵌入函数调用中,降低了库用户的工作量,且不须要对FSharp.Core.dll 的编译时依赖。

     

    // !!! C# Source !!!

    using System;

    usingSystem.Collections.Generic;

    usingStrangelights;

     

    class MapTwoClass{

      public static void MapTwo() {

        // define a list of names

       List<string> names = new List<string>(

          new string[] { "Aurelie", "Fabrice",

        "Ibrahima", "Lionel"});

     

        // call the F# demo function passing in an

        // anonymous delegate

       List<string> results =

         DemoModule.filterStringListDelegate(

          delegate(string s) {return s.StartsWith("A");}, names);

     

        // write the results to the console

        foreach (var s inresults) {

         Console.WriteLine(s);

        }

      }

    }

     

    演示样例的执行结果例如以下:

    Aurelie

  • 相关阅读:
    PYTHON核心编程第7章 7.5题
    openssl大漏洞
    运维之路
    组件嵌套+Mixin函数demo
    React初识(按钮点击+输入绑定)
    vue切换按钮(关闭消失型)
    动态发表之后的显示时间
    展开全部的实现
    前端进行后台数据的处理
    将项目上传到git上,并在测试服务器上运行
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/7048169.html
Copyright © 2011-2022 走看看