简体   繁体   English

我可以在F#中使用动态类型吗?

[英]Can I use dynamic types in F#?

.net4.0 .net4.0

mytest.py mytest.py

def Add (a, b):
    return a+b

I can use it in C# 4, like this: 我可以在C#4中使用它,如下所示:

        ScriptRuntime runtime = Python.CreateRuntime();
        dynamic script = runtime.UseFile("mytest.py");

        Console.WriteLine(script.Add(1, 3));

But, how can I use dynamic in F#? 但是,如何在F#中使用动态?

open System
open Microsoft.Scripting.Hosting
open IronPython.Hosting

let call a b=
    let runtime = Python.CreateRuntime()
    let script = runtime.UseFile("mytest.py")
    script.Add(a,b)

There is a module FSharp.Interop.Dynamic , on nuget that implements the dynamic operator using the dlr. nuget上有一个模块FSharp.Interop.Dynamic ,它使用dlr实现动态运算符。 So That: 以便:

open System
open Microsoft.Scripting.Hosting
open IronPython.Hosting
open EkonBenefits.FSharp.Dynamic

let call a b=
    let runtime = Python.CreateRuntime()
    let script = runtime.UseFile("mytest.py")
    script?Add(a,b)

It has several advantages over a lot of the snippets out there. 相对于其中的许多片段,它具有几个优点。

  • Performance it uses Dynamitey for the dlr call and Dynamitey implements caching of the callsites and is a PCL library 它使用Dynamitey进行dlr调用的性能,并且Dynamitey实现了对callite的缓存,并且是PCL库
  • Handles methods that return void, you'd get a binding exception if you didn't discard results of those when the binder was setup. 处理返回void的方法,如果在设置绑定程序时不丢弃那些结果,则会得到绑定异常。
  • The dlr handles the case of calling a delegate return by a function automatically, impromptu fsharp will also allow you to do the same with an FSharpFunc dlr处理通过函数自动调用委托返回的情况,即兴fsharp也将允许您使用FSharpFunc执行相同的操作
  • Adds an !? 加一个!? prefix operator to handle invoking directly dynamic objects and functions you don't have the type at runtime. 前缀运算符,用于处理在运行时没有类型的直接调用动态对象和函数。

    It's open source, Apache license, you can look at the implementation and it includes unit test example cases . 它是开源的Apache许可,您可以查看实现 ,其中包括单元测试示例案例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM