F# 动态对象访问

15

是否有一种类似于C#动态类型的方式可以访问F#中的DLR对象(例如DynamicObject子类实例)成员(属性和方法)?

3个回答

12

现在有一个模块可用于 NuGet,它使用 DLR 来实现动态运算符。 FSharp.Interop.Dynamic

与许多其他片段相比,它有几个优点。

  • 性能方面,它使用 Dynamitey 作为 DLR 调用来实现缓存,并且是一个 PCL 库。
  • 处理返回 void 的方法,在不舍弃这些结果的情况下,您将会得到绑定异常。
  • DLR 自动处理调用由函数返回的委托的情况,这也将允许您对 FSharpFunc 做同样的事情。
  • 添加了一个 !? 前缀运算符,以处理直接调用动态对象和函数,您在运行时没有该类型的情况下可以使用它们。

    它是开源的,使用 Apache 许可证,您可以查看 实现 和基本单元测试 示例


9
正如eriawan所说,?运算符的行为有点像C#中的dynamic类型。关于调用SQL的文章不依赖于DLR中的任何内容,因为您可以提供自己的实现?运算符,编译器直接使用它。
我还写了一个简短的示例,介绍如何使用DLR调用成员,可以在F#代码片段上找到,还有一个更复杂的版本由Matthew Podwysocki提供。另一个片段展示了如何使用它来调用标准的.NET类型使用反射
另请参见:

6
是的,可以。在F#中使用 运算符,并且在.NET 4.0中,它会以与C#和VB.NET动态类型相同的方式执行。首先,您可以阅读Tomas Petricek博客上的此示例Dynamic SQLDataReader:

http://tomasp.net/blog/dynamic-sql.aspx

以下是他文章中的一句引用:

In this article, we'll look how to use the dynamic operator to make the experience of using ADO.NET from F# dramatically better. Dynamic operator (there are actually two of them) are a simple way of supporting dynamic invoke in F#. We can use it to write code that looks almost like an ordinary method call or property access, but is resolved dynamically at runtime (using the name of the method or property). The following example shows what we'll be able to write at the end of this article:

// Call 'GetProducts' procedure with 'CategoryID' set to 1
use conn = new DynamicSqlConnection(connectionString)
use cmd = conn?GetProducts
cmd?CategoryID <- 1
conn.Open()

// Read all products and print their names
use reader = cmd.ExecuteReader()
while reader.Read() do
  printfn "Product: %s" reader?ProductName

If you ever tried to call a SQL stored procedure directly using the SqlCommand, then you can surely appreciate the elegance of this code snippet. Let's now take a look at a larger example and some of the neat tricks that make this possible...

如果您需要更多信息,可以阅读他的文章的其余部分。 在F#中愉快地进行动态编码 :)


谷歌居然没找到有关F# DLR/动态调度的链接,真奇怪。我的谷歌搜索技巧太差了。 - Rafael Munitić
不用谢。你是对的,它没有出现在谷歌查询中。 - Eriawan Kusumawardhono
1
实际上,F#中的'?'与C#中的dynamic并不相同,Tomas的存储过程示例也没有使用DLR。请参考Tomas的答案以及其他链接的问题。 - Mauricio Scheffer
当我找到问号后,我基本上就知道如何做DLR特定的事情了,但我同意他的答案更正确,抱歉。eriawan :) - Rafael Munitić

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接