F# dynamic object access

人盡茶涼 提交于 2019-11-28 21:29:42

There is a module now on nuget that uses the dlr to implement the dynamic operator. FSharp.Interop.Dynamic

It has several advantages over a lot of the snippets out there.

  • Performance it uses Dynamitey for the dlr call which implements caching and is a PCL library
  • Handles methods that return void, you'll get a binding exception if you don't discard results of those.
  • The dlr handles the case of calling a delegate return by a function automatically, this will also allow you to do the same with an 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 the basic unit test example cases.

Tomas Petricek

As eriawan mentioned, the ? operator behaves a bit like the dynamic type in C#. The article about calling SQL doesn't rely on anything from the DLR, because you can provide your own implementation of the ? operator and the compiler uses it directly.

I also wrote a brief example of how to use the ? operator to call members using DLR, which is available on F# snippets and there is a more sophisticated version by Matthew Podwysocki. Another snippet shows how to use it to call standard .NET types using Reflection.

See also:

Yes, it is. You can use ? operator in F#, and it will perform the same way in dynamic typing in C# and VB.NET in .NET 4.0. For a start, you can read this sample Dynamic SQLDataReader from Tomas Petricek's blog:

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

Here's a quote from his article:

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...

And for more info, you can read the rest of his article. Happy dynamic coding in F# :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!